Skip to main content

Overview

The useWebVoiceAgent hook provides a complete React integration for NAVAI voice agents. It manages the entire lifecycle of voice agent connections, including initialization, backend communication, function loading, and session management.

Import

import { useWebVoiceAgent } from '@navai/voice-frontend';

Signature

function useWebVoiceAgent(
  options: UseWebVoiceAgentOptions
): UseWebVoiceAgentResult

Parameters

options
UseWebVoiceAgentOptions
required
Configuration options for the voice agent hook.

Return Value

result
UseWebVoiceAgentResult
An object containing the voice agent state and control methods.

Example Usage

import { useWebVoiceAgent } from '@navai/voice-frontend';
import { useNavigate } from 'react-router-dom';

function VoiceAssistant() {
  const navigate = useNavigate();
  
  const voiceAgent = useWebVoiceAgent({
    navigate,
    moduleLoaders: {
      './functions/getProfile.ts': () => import('./functions/getProfile'),
      './functions/sendMessage.ts': () => import('./functions/sendMessage')
    },
    defaultRoutes: [
      {
        name: 'home',
        path: '/',
        description: 'Home page'
      },
      {
        name: 'profile',
        path: '/profile',
        description: 'User profile page',
        synonyms: ['perfil', 'account']
      },
      {
        name: 'settings',
        path: '/settings',
        description: 'Application settings',
        synonyms: ['config', 'preferences']
      }
    ],
    apiBaseUrl: 'https://api.myapp.com',
    modelOverride: 'gpt-4o-realtime-preview'
  });

  return (
    <div>
      <h2>Voice Assistant</h2>
      <p>Status: {voiceAgent.status}</p>
      
      {voiceAgent.error && (
        <div className="error">
          Error: {voiceAgent.error}
        </div>
      )}
      
      {voiceAgent.isConnected ? (
        <button onClick={voiceAgent.stop}>
          Stop Voice Agent
        </button>
      ) : (
        <button 
          onClick={voiceAgent.start}
          disabled={voiceAgent.isConnecting}
        >
          {voiceAgent.isConnecting ? 'Connecting...' : 'Start Voice Agent'}
        </button>
      )}
    </div>
  );
}

Lifecycle

  1. Initialization: Hook sets up memoized backend client and runtime config promise
  2. Start: Call start() to begin connection sequence
  3. Connecting: Backend secret created, functions loaded, agent built
  4. Connected: Realtime session established with OpenAI
  5. Stop: Call stop() to gracefully close the session
  6. Cleanup: Hook automatically calls stop() on unmount

Error Handling

const voiceAgent = useWebVoiceAgent(options);

if (voiceAgent.status === 'error') {
  console.error('Voice agent error:', voiceAgent.error);
  // Handle error - show UI message, retry, etc.
}

Source Reference

Defined in: packages/voice-frontend/src/useWebVoiceAgent.ts:52

Build docs developers (and LLMs) love