Skip to main content

Overview

createNavaiMobileBackendClient creates a client for communicating with your backend API. It handles client secret generation, function listing, and function execution.

Import

import { createNavaiMobileBackendClient } from '@navai/voice-mobile';

Usage

import { createNavaiMobileBackendClient } from '@navai/voice-mobile';

const backendClient = createNavaiMobileBackendClient({
  apiBaseUrl: 'https://api.example.com',
  env: {
    NAVAI_API_URL: 'https://api.example.com'
  }
});

// Create client secret for realtime connection
const { value, expires_at } = await backendClient.createClientSecret({
  model: 'gpt-realtime',
  voice: 'alloy'
});

// List available backend functions
const { functions, warnings } = await backendClient.listFunctions();

// Execute a backend function
const result = await backendClient.executeFunction({
  functionName: 'get_weather',
  payload: { location: 'San Francisco' }
});

Type Signature

function createNavaiMobileBackendClient(
  options?: CreateNavaiMobileBackendClientOptions
): NavaiMobileBackendClient

Parameters

options
CreateNavaiMobileBackendClientOptions
Configuration options for the backend client

Return Value

createClientSecret
(input?: CreateRealtimeClientSecretInput) => Promise<CreateRealtimeClientSecretResult>
Create a client secret for OpenAI Realtime API connection.
listFunctions
() => Promise<BackendFunctionsResult>
List available backend functions.
executeFunction
(input: ExecuteNavaiBackendFunctionInput) => Promise<unknown>
Execute a backend function.Returns the function result (type depends on the function).Throws if function execution fails or returns an error.

API Endpoints

The backend client expects these endpoints:

POST /navai/realtime/client-secret

Create ephemeral client secret for OpenAI Realtime API. Request:
{
  "model": "gpt-realtime",
  "voice": "alloy"
}
Response:
{
  "value": "client_secret_...",
  "expires_at": 1234567890
}

GET /navai/functions

List available backend functions. Response:
{
  "items": [
    {
      "name": "get_weather",
      "description": "Get current weather",
      "source": "backend"
    }
  ],
  "warnings": []
}

POST /navai/functions/execute

Execute a backend function. Request:
{
  "function_name": "get_weather",
  "payload": { "location": "San Francisco" }
}
Response (Success):
{
  "ok": true,
  "result": {
    "temperature": 72,
    "condition": "sunny"
  }
}
Response (Error):
{
  "ok": false,
  "error": "Function execution failed",
  "details": "Location not found"
}

Examples

Basic Client

import { createNavaiMobileBackendClient } from '@navai/voice-mobile';

const client = createNavaiMobileBackendClient({
  apiBaseUrl: 'https://api.example.com'
});

const secret = await client.createClientSecret();
console.log('Secret expires at:', new Date(secret.expires_at * 1000));

With Environment Variables

import { createNavaiMobileBackendClient, resolveNavaiMobileEnv } from '@navai/voice-mobile';
import Config from 'react-native-config';

const env = resolveNavaiMobileEnv({
  sources: [Config, process.env]
});

const client = createNavaiMobileBackendClient({ env });
// Uses NAVAI_API_URL from Config or process.env

Custom Endpoints

const client = createNavaiMobileBackendClient({
  apiBaseUrl: 'https://api.example.com',
  clientSecretPath: '/api/voice/secret',
  functionsListPath: '/api/voice/functions',
  functionsExecutePath: '/api/voice/execute'
});

Error Handling

try {
  const result = await client.executeFunction({
    functionName: 'get_weather',
    payload: { location: 'Invalid' }
  });
  console.log('Result:', result);
} catch (error) {
  console.error('Execution failed:', error.message);
}

Function Discovery

const { functions, warnings } = await client.listFunctions();

if (warnings.length > 0) {
  console.warn('Warnings:', warnings);
}

console.log('Available functions:');
functions.forEach(fn => {
  console.log(`- ${fn.name}: ${fn.description}`);
});

Custom Fetch (for testing)

const mockFetch = jest.fn(async (url, options) => {
  return {
    ok: true,
    json: async () => ({ value: 'mock_secret' })
  };
});

const client = createNavaiMobileBackendClient({
  fetchImpl: mockFetch
});

const secret = await client.createClientSecret();
// Uses mockFetch instead of global fetch

Error Handling

The client throws errors in these cases:
MethodError ConditionError Message
createClientSecretHTTP errorResponse text or HTTP {status}
createClientSecretInvalid response"Invalid client-secret response."
listFunctionsHTTP errorReturns empty functions with warning
listFunctionsParse errorReturns empty functions with warning
executeFunctionHTTP errorResponse text or HTTP {status}
executeFunctionInvalid response"Invalid backend function response."
executeFunctionFunction errorpayload.details or payload.error

Implementation Notes

URL Construction

The client constructs URLs by:
  1. Removing trailing slashes from base URL
  2. Ensuring path starts with /
  3. Joining: {baseUrl}{path}

Response Parsing

  • createClientSecret: Expects { value: string, expires_at?: number }
  • listFunctions: Expects { items: [], warnings: [] }, gracefully handles errors
  • executeFunction: Expects { ok: true, result: any } or { ok: false, error: string }

Fetch Fallback

If fetchImpl is not provided, uses global fetch. This allows for:
  • Custom fetch implementations
  • Testing with mock fetch
  • Network layer customization

Best Practices

  1. URL Configuration: Use environment variables for API URL
  2. Error Handling: Always wrap API calls in try-catch
  3. Secret Expiration: Monitor expires_at and refresh before expiry
  4. Function Discovery: Cache function list to reduce API calls
  5. Timeout Handling: Configure reasonable timeouts for fetch

See Also

Build docs developers (and LLMs) love