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

# Example: Placing an outbound call

> This example starts a VoxEngine session, places an outbound PSTN call, and bridges audio to OpenAI Realtime once the callee answers.

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

This example starts a VoxEngine session, places an outbound PSTN call, and bridges audio to OpenAI Realtime once the callee answers. 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

* Store your OpenAI API key in Voximplant [Secrets](/platform/voxengine/secrets) under `OPENAI_API_KEY`.
* Ensure outbound calling is enabled for your Voximplant application and that your caller ID is verified.

## Outbound call parameters

The example expects destination and caller ID in `customData` (read via `VoxEngine.customData()`):

**`Custom data example`**

```json title="Custom data example"
{"destination":"+15551234567","callerId":"+15557654321"}
```

## Launch the routing rule

For quick testing, you can start this outbound scenario from the Voximplant Control Panel:

1. Open your Voximplant application and go to the **Routing** tab.
2. Select the routing rule that has this scenario attached.
3. Click **Run**.
4. Provide **Custom data** (max 200 bytes) with `destination` and `callerId`:

**`Custom data example`**

```json title="Custom data example"
{"destination":"+15551234567","callerId":"+15557654321"}
```

For production, start the routing rule with the Management API [`startScenarios`](/api-reference/management-api/reference/scenarios/start-scenarios) method. Pass `rule_id` and the same JSON string in `script_custom_data`.

## Alternate outbound destinations

This example uses `VoxEngine.callPSTN(...)` for PSTN dialing. You can also route outbound calls to other destination types in VoxEngine:

* **SIP** (`VoxEngine.callSIP`): dial a SIP URI to reach a PBX, carrier, SIP trunk, or other SIP endpoint.
* **WhatsApp** (`VoxEngine.callWhatsappUser`): place a WhatsApp Business-initiated call (requires a WhatsApp Business account and enabled numbers).
* **Voximplant users** (`VoxEngine.callUser`): calls another app user inside the same Voximplant application such as web SDK, mobile SDK, or SIP user.

Relevant guides:

* [SIP calling options](/getting-started/network-options/sip)
* [Voximplant users calling options](/getting-started/network-options/web-mobile)
* [WhatsApp calling options](/getting-started/network-options/whatsapp)

## Session setup

The outbound call setup is shared between versions. Only the Realtime model and session configuration change.

#### GPT Realtime 2.1

The example configures the OpenAI Realtime session with a short 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", 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

After the callee answers, the example bridges audio both ways:

**`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-place-outbound-call.js"} maxLines={0}
/**
 * Voximplant + OpenAI Realtime API connector demo
 * Scenario: place an outbound PSTN call and bridge it to OpenAI Realtime 2.1.
 */

require(Modules.OpenAI);

const SYSTEM_PROMPT = `
You are Voxi, a concise phone assistant for outbound calls.
Keep responses short and helpful.
`;

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", interrupt_response: true},
            },
            output: {
                voice: "alloy",
            },
        },
    },
};

const MAX_CALL_MS = 2 * 60 * 1000;

VoxEngine.addEventListener(AppEvents.Started, async () => {
    let call;
    let voiceAIClient;
    let hangupTimer;

    try {
        // Custom data example: {"destination":"+15551234567","callerId":"+15557654321"}
        const {destination, callerId} = JSON.parse(VoxEngine.customData());

        call = VoxEngine.callPSTN(destination, callerId);
        // Alternative outbound paths (uncomment to use):
        // call = VoxEngine.callUser({username: destination, callerid: callerId});
        // call = VoxEngine.callSIP(`sip:${destination}@your-sip-domain`, callerId);
        // call = VoxEngine.callWhatsappUser({number: destination, callerid: callerId});

        call.addEventListener(CallEvents.Failed, () => VoxEngine.terminate());
        call.addEventListener(CallEvents.Disconnected, () => {
            if (hangupTimer) clearTimeout(hangupTimer);
            VoxEngine.terminate();
        });

        call.addEventListener(CallEvents.Connected, async () => {
            hangupTimer = setTimeout(() => {
                Logger.write("===HANGUP_TIMER===");
                call.hangup();
            }, MAX_CALL_MS);

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

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

            voiceAIClient.addEventListener(OpenAI.RealtimeAPIEvents.SessionUpdated, () => {
                VoxEngine.sendMediaBetween(call, voiceAIClient);
                voiceAIClient.conversationItemCreate({
                    item: {
                        type: "message",
                        role: "user",
                        content: [
                            {
                                type: "input_text",
                                text: "The phone call just connected. "
                                    + 'Say exactly: "Hello! This is Voxi. How can I help today?"',
                            },
                        ],
                    },
                });
                voiceAIClient.responseCreate({});
            });

            voiceAIClient.addEventListener(
                OpenAI.RealtimeAPIEvents.InputAudioBufferSpeechStarted,
                () => {
                    Logger.write("===BARGE-IN: OpenAI.InputAudioBufferSpeechStarted===");
                    voiceAIClient.clearMediaBuffer();
                },
            );

            // Consolidated "log-only" handlers
            [
                OpenAI.RealtimeAPIEvents.ResponseCreated,
                OpenAI.RealtimeAPIEvents.ResponseDone,
                OpenAI.RealtimeAPIEvents.ResponseOutputAudioDone,
                OpenAI.RealtimeAPIEvents.ConversationItemInputAudioTranscriptionCompleted,
                OpenAI.RealtimeAPIEvents.ResponseOutputAudioTranscriptDone,
                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();
    }
});

```

#### GPT Realtime 1.5

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

require(Modules.OpenAI);

const OPENAI_MODEL = "gpt-realtime-1.5";

const SYSTEM_PROMPT = `
You are Voxi, a concise phone assistant for outbound calls.
Keep responses short and helpful.
`;

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

const MAX_CALL_MS = 2 * 60 * 1000;

VoxEngine.addEventListener(AppEvents.Started, async () => {
    let call;
    let voiceAIClient;
    let hangupTimer;

    try {
        // Custom data example: {"destination":"+15551234567","callerId":"+15557654321"}
        const {destination, callerId} = JSON.parse(VoxEngine.customData());

        call = VoxEngine.callPSTN(destination, callerId);
        // Alternative outbound paths (uncomment to use):
        // call = VoxEngine.callUser({username: destination, callerid: callerId});
        // call = VoxEngine.callSIP(`sip:${destination}@your-sip-domain`, callerId);
        // call = VoxEngine.callWhatsappUser({number: destination, callerid: callerId});

        call.addEventListener(CallEvents.Failed, () => VoxEngine.terminate());
        call.addEventListener(CallEvents.Disconnected, () => {
            if (hangupTimer) clearTimeout(hangupTimer);
            VoxEngine.terminate();
        });

        call.addEventListener(CallEvents.Connected, async () => {
            hangupTimer = setTimeout(() => {
                Logger.write("===HANGUP_TIMER===");
                call.hangup();
            }, MAX_CALL_MS);

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

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

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

            voiceAIClient.addEventListener(
                OpenAI.RealtimeAPIEvents.InputAudioBufferSpeechStarted,
                () => {
                    Logger.write("===BARGE-IN: OpenAI.InputAudioBufferSpeechStarted===");
                    voiceAIClient.clearMediaBuffer();
                },
            );

            // Consolidated "log-only" handlers
            [
                OpenAI.RealtimeAPIEvents.ResponseCreated,
                OpenAI.RealtimeAPIEvents.ResponseDone,
                OpenAI.RealtimeAPIEvents.ResponseOutputAudioDone,
                OpenAI.RealtimeAPIEvents.ConversationItemInputAudioTranscriptionCompleted,
                OpenAI.RealtimeAPIEvents.ResponseOutputAudioTranscriptDone,
                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)
* [Answering an incoming call with OpenAI Realtime](/voice-ai-orchestration/openai/inbound)
* [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)
* [Start scenarios with the Management API](/api-reference/management-api/reference/scenarios/start-scenarios)