> For a complete documentation index, fetch https://docs.voximplant.ai/llms.txt

# Example: Answering an incoming call

> This example answers an inbound Voximplant call and bridges audio to OpenAI Realtime for speech‑to‑speech conversations.

> For the complete documentation index, see [llms.txt](/llms.txt).

This example answers an inbound Voximplant call and bridges audio to OpenAI Realtime for speech-to-speech conversations. Select a model version to keep the session configuration and complete scenario synchronized. `gpt-realtime-2.1` is the default for new applications.

**Jump to the [Full VoxEngine scenarios](#full-voxengine-scenarios).**

## Prerequisites

* Set up an inbound entrypoint for the caller:
  * [Phone number](/platform/voxengine/phone-numbers)
  * [WhatsApp](/getting-started/network-options/whatsapp)
  * [SIP user / SIP registration](/getting-started/network-options/sip)
  * [App user](/platform/voxengine/users) - also see the [Web & Mobile](/getting-started/network-options/web-mobile) client SDK options
* Create a [routing rule](/platform/voxengine/routing-rules) that points the destination (phone number / WhatsApp / SIP username / app user alias) to this scenario.
* Store your OpenAI API key in Voximplant [Secrets](/platform/voxengine/secrets) under `OPENAI_API_KEY`.

## Session setup

> **Info**
>
> `gpt-realtime-2` and above introduced some breaking changes to the `gpt-realtime-1.x` session configuration object.
> Make sure to select the appropriate version in the examples below.

#### GPT Realtime 2.1

The example configures the OpenAI Realtime session with a system prompt, enables semantic VAD, and uses low reasoning effort.

**`GPT Realtime 2.1 session setup`**

```js title="GPT Realtime 2.1 session setup"
voiceAIClient.sessionUpdate({
  session: {
    type: "realtime",
    model: "gpt-realtime-2.1",
    instructions: SYSTEM_PROMPT,
    reasoning: { effort: "low" },
    output_modalities: ["audio"],
    audio: {
      input: {
        turn_detection: {
          type: "semantic_vad",
          eagerness: "auto",
          create_response: true,
          interrupt_response: true,
        },
      },
      output: {
        voice: "alloy",
      },
    },
  },
});
```

#### GPT Realtime 1.5

The example configures the OpenAI Realtime session with a short system prompt, a voice, and server VAD.

**`GPT Realtime 1.5 session setup`**

```js title="GPT Realtime 1.5 session setup"
voiceAIClient.sessionUpdate({
  session: {
    type: "realtime",
    instructions: SYSTEM_PROMPT,
    voice: "alloy",
    output_modalities: ["audio"],
    turn_detection: { type: "server_vad", interrupt_response: true },
  },
});
```

## Connect call audio

Once the session is ready, bridge audio both ways between the call and OpenAI:

**`Connect call audio`**

```js title="Connect call audio"
VoxEngine.sendMediaBetween(call, voiceAIClient);
```

## Barge-in

The scenario clears buffered model audio whenever OpenAI detects caller speech:

**`Barge-in`**

```js title="Barge-in"
voiceAIClient.addEventListener(OpenAI.RealtimeAPIEvents.InputAudioBufferSpeechStarted, () => {
  voiceAIClient.clearMediaBuffer();
});
```

## Full VoxEngine scenarios

#### GPT Realtime 2.1

```javascript title={"voxeengine-openai-answer-incoming-call.js"} maxLines={0}
/**
 * Voximplant + OpenAI Realtime API connector demo
 * Scenario: answer an incoming call and bridge it to OpenAI Realtime 2.1.
 */

require(Modules.OpenAI);

const SYSTEM_PROMPT = `
You are Voxi, a helpful voice assistant for phone callers.
Keep responses short and telephony-friendly (usually 1-2 sentences).
`;

const SESSION_CONFIG = {
    session: {
        type: "realtime",
        model: "gpt-realtime-2.1",
        instructions: SYSTEM_PROMPT,
        reasoning: {effort: "low"},
        output_modalities: ["audio"],
        audio: {
            input: {
                turn_detection: {
                    type: "semantic_vad",
                    eagerness: "auto",
                    create_response: true,
                    interrupt_response: true,
                },
            },
            output: {
                voice: "alloy",
            },
        },
    },
};

VoxEngine.addEventListener(AppEvents.CallAlerting, async ({call}) => {
    let voiceAIClient;
    const eventPayload = (event) => event?.data?.payload || event?.data || {};

    const terminate = () => {
        voiceAIClient?.close();
        VoxEngine.terminate();
    };

    call.addEventListener(CallEvents.Disconnected, terminate);
    call.addEventListener(CallEvents.Failed, terminate);

    try {
        const providerApiKey = VoxEngine.getSecretValue("OPENAI_API_KEY");
        if (!providerApiKey) throw new Error("Set OPENAI_API_KEY in Voximplant Secrets");

        call.answer();

        voiceAIClient = await OpenAI.createRealtimeAPIClient({
            apiKey: providerApiKey,
            model: "gpt-realtime-2.1",
            onWebSocketClose: terminate,
        });

        voiceAIClient.addEventListener(OpenAI.RealtimeAPIEvents.SessionCreated, () => {
            voiceAIClient.sessionUpdate(SESSION_CONFIG);
        });

        voiceAIClient.addEventListener(OpenAI.RealtimeAPIEvents.SessionUpdated, () => {
            VoxEngine.sendMediaBetween(call, voiceAIClient);    // media connected
            voiceAIClient.conversationItemCreate({              // request a greeting
                item: {
                    type: "message",
                    role: "user",
                    content: [
                        {
                            type: "input_text",
                            text: "The phone call just connected. "
                                + 'Say exactly: "Hello! How can I help today?"',
                        },
                    ],
                },
            });
            voiceAIClient.responseCreate({});       // ask for the response now
        });

        // Barge-in: clear buffered audio when the caller starts speaking
        voiceAIClient.addEventListener(OpenAI.RealtimeAPIEvents.InputAudioBufferSpeechStarted, () => {
            Logger.write("===BARGE-IN: OpenAI.InputAudioBufferSpeechStarted===");
            voiceAIClient.clearMediaBuffer();
        });

        voiceAIClient.addEventListener(
            OpenAI.RealtimeAPIEvents.ConversationItemInputAudioTranscriptionCompleted,
            (event) => {
                const payload = eventPayload(event);
                const transcript = payload.transcript || payload.text || payload.delta;
                if (transcript) Logger.write(`===USER=== ${transcript}`);
            },
        );

        voiceAIClient.addEventListener(
            OpenAI.RealtimeAPIEvents.ResponseOutputAudioTranscriptDone,
            (event) => {
                const payload = eventPayload(event);
                const transcript = payload.transcript || payload.text;
                if (transcript) Logger.write(`===AGENT=== ${transcript}`);
            },
        );

        // Consolidated "log-only" handlers - key OpenAI/VoxEngine debugging events
        [
            OpenAI.RealtimeAPIEvents.ResponseCreated,
            OpenAI.RealtimeAPIEvents.ResponseDone,
            OpenAI.RealtimeAPIEvents.ResponseOutputAudioDone,
            OpenAI.RealtimeAPIEvents.ConnectorInformation,
            OpenAI.RealtimeAPIEvents.HTTPResponse,
            OpenAI.RealtimeAPIEvents.Error,
            OpenAI.RealtimeAPIEvents.WebSocketError,
            OpenAI.RealtimeAPIEvents.Unknown,
            OpenAI.Events.WebSocketMediaStarted,
            OpenAI.Events.WebSocketMediaEnded,
        ].forEach((eventName) => {
            voiceAIClient.addEventListener(eventName, (event) => {
                Logger.write(`===${event.name}===`);
                if (event?.data) Logger.write(JSON.stringify(event.data));
            });
        });
    } catch (error) {
        Logger.write("===UNHANDLED_ERROR===");
        Logger.write(JSON.stringify(error));
        terminate();
    }
});

```

#### GPT Realtime 1.5

```javascript title={"voxeengine-openai-inbound-1-5.js"} maxLines={0}
/**
 * Voximplant + OpenAI Realtime API connector demo
 * Scenario: answer an incoming call and bridge it to OpenAI Realtime 1.5.
 */

require(Modules.OpenAI);

const SYSTEM_PROMPT = `
You are Voxi, a helpful voice assistant for phone callers.
Keep responses short and telephony-friendly (usually 1-2 sentences).
`;

const SESSION_CONFIG = {
    session: {
        type: "realtime",
        instructions: SYSTEM_PROMPT,
        voice: "alloy",
        output_modalities: ["audio"],
        turn_detection: {type: "server_vad", interrupt_response: true},
    },
};

VoxEngine.addEventListener(AppEvents.CallAlerting, async ({call}) => {
    let voiceAIClient;

    call.addEventListener(CallEvents.Disconnected, () => VoxEngine.terminate());
    call.addEventListener(CallEvents.Failed, () => VoxEngine.terminate());

    try {
        call.answer();
        // call.record({hd_audio: true, stereo: true}); // Optional: record the call

        voiceAIClient = await OpenAI.createRealtimeAPIClient({
            apiKey: VoxEngine.getSecretValue("OPENAI_API_KEY"),
            model: "gpt-realtime-1.5",
            onWebSocketClose: (event) => {
                Logger.write("===OpenAI.WebSocket.Close===");
                if (event) Logger.write(JSON.stringify(event));
                VoxEngine.terminate();
            },
        });

        //---------------------- Event handlers -----------------------
        voiceAIClient.addEventListener(OpenAI.RealtimeAPIEvents.SessionCreated, () => {
            voiceAIClient.sessionUpdate(SESSION_CONFIG);
        });

        voiceAIClient.addEventListener(OpenAI.RealtimeAPIEvents.SessionUpdated, () => {
            VoxEngine.sendMediaBetween(call, voiceAIClient);
            voiceAIClient.responseCreate({instructions: "Hello! How can I help today?"});
        });

        // Barge-in: clear buffered audio when the caller starts speaking
        voiceAIClient.addEventListener(OpenAI.RealtimeAPIEvents.InputAudioBufferSpeechStarted, () => {
            Logger.write("===BARGE-IN: OpenAI.InputAudioBufferSpeechStarted===");
            voiceAIClient.clearMediaBuffer();
        });

        voiceAIClient.addEventListener(
            OpenAI.RealtimeAPIEvents.ConversationItemInputAudioTranscriptionCompleted,
            (event) => {
                const {transcript} = event.data.payload;
                if (transcript) Logger.write(`===USER=== ${transcript}`);
            },
        );

        voiceAIClient.addEventListener(
            OpenAI.RealtimeAPIEvents.ResponseOutputAudioTranscriptDelta,
            (event) => {
                const {delta} = event.data.payload;
                if (delta) Logger.write(`===AGENT_DELTA=== ${delta}`);
            },
        );

        voiceAIClient.addEventListener(
            OpenAI.RealtimeAPIEvents.ResponseOutputAudioTranscriptDone,
            (event) => {
                const {transcript} = event.data.payload;
                if (transcript) Logger.write(`===AGENT=== ${transcript}`);
            },
        );

        // Consolidated "log-only" handlers - key OpenAI/VoxEngine debugging events
        [
            OpenAI.RealtimeAPIEvents.ResponseCreated,
            OpenAI.RealtimeAPIEvents.ResponseDone,
            OpenAI.RealtimeAPIEvents.ResponseOutputAudioDone,
            OpenAI.RealtimeAPIEvents.ConnectorInformation,
            OpenAI.RealtimeAPIEvents.HTTPResponse,
            OpenAI.RealtimeAPIEvents.WebSocketError,
            OpenAI.RealtimeAPIEvents.Unknown,
            OpenAI.Events.WebSocketMediaStarted,
            OpenAI.Events.WebSocketMediaEnded,
        ].forEach((eventName) => {
            voiceAIClient.addEventListener(eventName, (event) => {
                Logger.write(`===${event.name}===`);
                if (event?.data) Logger.write(JSON.stringify(event.data));
            });
        });
    } catch (error) {
        Logger.write("===UNHANDLED_ERROR===");
        Logger.write(error);
        voiceAIClient?.close();
        VoxEngine.terminate();
    }
});

```

## More information

* [OpenAI connector overview](/voice-ai-orchestration/openai/overview)
* [Placing an outbound call with OpenAI Realtime](/voice-ai-orchestration/openai/outbound)
* [Function calling with OpenAI Realtime](/voice-ai-orchestration/openai/function-calling)
* [VoxEngine OpenAI module API reference](/api-reference/voxengine/openai)
* [Current OpenAI models](https://developers.openai.com/api/docs/models)
* [OpenAI Realtime API reference](https://developers.openai.com/api/docs/api-reference/realtime)