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

# Example: Answering an incoming call

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

## Overview

This minimal example answers an inbound call and connects it to the Grok Voice Agent API with only core settings and barge-in support—no extra tools or function calling.

**⬇️ Jump to the [Full VoxEngine scenario](#full-voxengine-scenario).**

## 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)
* 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 xAI API key in Voximplant [Secrets](/platform/voxengine/secrets) under `XAI_API_KEY`.

## Architecture

```mermaid
graph LR
  Caller[PSTN/SIP/WhatsApp/App users/WebRTC] --> VoxEngine[VoxEngine Scenario]
  VoxEngine -->|WebSocket Media| Grok[Grok Voice Agent API]
  Grok --> VoxEngine
  VoxEngine --> Caller
```

## Usage highlights

* Create a `VoiceAgentAPIClient` with `XAI.createVoiceAgentAPIClient(...)`.
* Select the Grok voice model with `model: "grok-voice-think-fast-1.0"`, or set `GROK_MODEL` to another xAI Voice Agent model supported by your account.
* Configure the session with `voice`, `turn_detection`, and a short `instructions` prompt.
* Bridge audio with `VoxEngine.sendMediaBetween(call, client)`.
* Enable barge-in by clearing the media buffer when the caller starts speaking.

### Turn detection & barge-in

When `InputAudioBufferSpeechStarted` fires, clear the media buffer so the caller can interrupt the agent:

```js
voiceAgentAPIClient.addEventListener(
  XAI.VoiceAgentAPIEvents.InputAudioBufferSpeechStarted,
  () => voiceAgentAPIClient.clearMediaBuffer()
);
```

## Configure before you run

* Set `XAI_API_KEY` in Voximplant [Secrets](/platform/voxengine/secrets).
* Change `GROK_MODEL` if you want to use a different Grok voice model.
* Adjust the `SYSTEM_PROMPT` in the example to match your brand voice and guardrails.

## Try it

Suggested test prompts:

* "Hello"
* "What can you help me with?"
* "Goodbye."

## Notes

[See the VoxEngine API Reference for more details](/api-reference/voxengine/xai).

## Full VoxEngine scenario

```javascript title={"voxeengine-grok-answer-incoming-call.js"} maxLines={0}
require(Modules.XAI);
// Pin the xAI Voice Agent model used by this example.
const GROK_MODEL = "grok-voice-think-fast-1.0";
const SYSTEM_PROMPT = `
  You are Voxi, a concise phone agent for Voximplant callers.
  Keep answers brief and helpful. If you do not know, say so and offer to connect them to a human.
`;

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

    // Termination functions - add cleanup and logging as needed
    call.addEventListener(CallEvents.Disconnected, ()=>VoxEngine.terminate());
    call.addEventListener(CallEvents.Failed, ()=>VoxEngine.terminate());

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

    try {
        voiceAIClient = await XAI.createVoiceAgentAPIClient({
            xAIApiKey: VoxEngine.getSecretValue("XAI_API_KEY"),
            model: GROK_MODEL,
            onWebSocketClose: (event) => {
                Logger.write("===XAI.WebSocket.Close===");
                if (event) Logger.write(JSON.stringify(event));
                VoxEngine.terminate();
            },
        });

        // Set up the session once created
        voiceAIClient.addEventListener(
            XAI.VoiceAgentAPIEvents.ConversationCreated,
            () => {
                voiceAIClient.sessionUpdate({
                    session: {
                        voice: "Ara",
                        turn_detection: {type: "server_vad"},
                        instructions: SYSTEM_PROMPT,
                    },
                });
            },
        );

        // Wait for Grok setup, then bridge audio and trigger the greeting
        voiceAIClient.addEventListener(
            XAI.VoiceAgentAPIEvents.SessionUpdated,
            () => {
                VoxEngine.sendMediaBetween(call, voiceAIClient);
                voiceAIClient.responseCreate({instructions: "Hello! How can I help today?"});
            },
        );

        // Simple barge-in: clear buffered audio when caller starts speaking
        voiceAIClient.addEventListener(
            XAI.VoiceAgentAPIEvents.InputAudioBufferSpeechStarted,
            () => voiceAIClient.clearMediaBuffer(),
        );

        // -------------------- Log Other Events --------------------
        [
            CallEvents.FirstAudioPacketReceived,
            XAI.Events.WebSocketMediaStarted,
            XAI.Events.WebSocketMediaEnded,
            XAI.VoiceAgentAPIEvents.ConnectorInformation,
            XAI.VoiceAgentAPIEvents.ResponseCreated,
            XAI.VoiceAgentAPIEvents.ResponseOutputItemAdded,
            XAI.VoiceAgentAPIEvents.ResponseOutputItemDone,
            XAI.VoiceAgentAPIEvents.ResponseOutputAudioTranscriptDelta,
            XAI.VoiceAgentAPIEvents.ResponseOutputAudioTranscriptDone,
            XAI.VoiceAgentAPIEvents.ResponseOutputAudioDone,
            XAI.VoiceAgentAPIEvents.ResponseDone,
            XAI.VoiceAgentAPIEvents.InputAudioBufferSpeechStopped,
            XAI.VoiceAgentAPIEvents.InputAudioBufferCommitted,
            XAI.VoiceAgentAPIEvents.ConversationItemAdded,
            XAI.VoiceAgentAPIEvents.ConversationItemInputAudioTranscriptionCompleted,
            XAI.VoiceAgentAPIEvents.WebSocketError,
            XAI.VoiceAgentAPIEvents.Unknown,
        ].forEach((evtName) => {
            voiceAIClient.addEventListener(evtName, (e) => {
                Logger.write(`===${e.name}===>${JSON.stringify(e)}`);
            });
        });

    } catch (error) {
        Logger.write("===SOMETHING_WENT_WRONG===");
        Logger.write(error);
        VoxEngine.terminate();
    }
});

```