> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.withpaygent.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.withpaygent.com/_mcp/server.

# Voice Tracking

Paygent provides a robust Session-based flow for tracking complex Voice AI interactions, including STT, LLM, and TTS usage.

> **Warning**
>
> **Prerequisite:** Complete the [Voice Agent Setup](/documentation/voice-tracking/voice-agent-setup) before implementing voice tracking.

## Complete Voice Session Flow

This example shows how to manage a voice session from start to finish:

#### Python

**`voice_session_flow.py`**

```python title="voice_session_flow.py"
import time
from paygent_sdk import Client
from paygent_sdk.models import CustomerCreateOrGetRequest
from paygent_sdk.constants import ServiceProvider, DeepgramSTTModels, AmazonPollyTTSModels

client = Client(api_key="your-paygent-api-key")

customer_id = "customer-123"
agent_id = "voice-agent-id"

# 1. Create or Get Customer (Automated)
client.create_or_get_customer(CustomerCreateOrGetRequest(
    name="Customer Name",
    external_id=customer_id
))

# 2. Define a unique session ID
session_id = f"voice_call_{int(time.time() * 1000)}"

# 3. Initialize Voice Session
client.initialize_voice_session(session_id, agent_id, customer_id)

# 4. Track User Speech (STT Usage)
client.track_voice_stt(session_id, {
    'serviceProvider': ServiceProvider.DEEPGRAM,
    'model': DeepgramSTTModels.NOVA_2,
    'plan': 'default',
    'audioDuration': 0.333 # audio duration in minutes (e.g. 20 seconds → 20/60)
})

# 5. Track AI Processing (LLM Usage)
client.track_voice_llm(session_id, {
    'serviceProvider': ServiceProvider.OPENAI,
    'model': 'gpt-4o',
    'plan': 'default',
    'promptTokens': 1000,
    'completionTokens': 500
})

# 6. Track AI Speech (TTS Usage)
client.track_voice_tts(session_id, {
    'serviceProvider': ServiceProvider.AMAZON_POLLY,
    'model': AmazonPollyTTSModels.NEURAL,
    'plan': 'default',
    'character_count': 28000
})

# 7. Final Step: Set Indicator with Call Duration (Minutes)
client.set_voice_indicator(session_id, "voice_call_completed", 0.5)
```

#### Node.js

**`voice-session-flow.ts`**

```typescript title="voice-session-flow.ts"
import { 
    PaygentClient, 
    ServiceProvider, 
    DeepgramSTTModels, 
    AmazonPollyTTSModels 
} from '@paygent_org/paygent-sdk-node';

const client = PaygentClient.newClient(process.env.PAYGENT_API_KEY);

// 1. Create or Get Customer (Automated)
await client.createOrGetCustomer({
    name: "customer_name",
    externalId: "customer_123",
});

// 2. Define a unique session ID
// Use your own unique session ID for this customer (e.g., call SID or UUID)
const sessionId = `voice_call_${Date.now()}`;
const agentId = "your-agent-id";
const customerId = "customer_123";

// 3. Initialize Voice Session
await client.initializeVoiceSession(sessionId, agentId, customerId);

// 4. Track User Speech (STT Usage) - duration in minutes
await client.trackVoiceStt(sessionId, {
    serviceProvider: ServiceProvider.DEEPGRAM,
    model: DeepgramSTTModels.NOVA_2,
    audioDuration: 0.333 // e.g. 20 seconds → 20/60 minutes
});

// 5. Track AI Processing (LLM Usage)
await client.trackVoiceLlm(sessionId, {
    serviceProvider: ServiceProvider.OPENAI,
    model: 'gpt-4o',
    promptTokens: 1000,
    completionTokens: 500
});

// 6. Track AI Speech (TTS Usage) - 28,000 characters
await client.trackVoiceTts(sessionId, {
    serviceProvider: ServiceProvider.AMAZON_POLLY,
    model: AmazonPollyTTSModels.NEURAL,
    characterCount: 28000
});

// 7. Final Step: Set Indicator with Call Duration (Minutes)
// e.g., Set an indicator for a 10-minute call
await client.setVoiceIndicator(sessionId, "voice_call_completed", 10);
```

#### Go

**`voice_session.go`**

```go title="voice_session.go"
package main

import (
    "fmt"
    "time"
    paygent "github.com/paygent-org/paygent-sdk-go"
)

func main() {
    client := paygent.NewClient("your-paygent-api-key")

    customerID := "customer-123"
    agentID := "voice-agent-id"

    // 1. Create or Get Customer (Automated)
    client.CreateOrGetCustomer(paygent.CustomerCreateOrGetRequest{
        ExternalID: customerID,
        Name:       "Customer Name",
    })

    // 2. Define a unique session ID
    sessionID := fmt.Sprintf("voice_session_%d", time.Now().Unix())
    
    // 3. Initialize Voice Session
    client.InitializeVoiceSession(sessionID, agentID, customerID)

    // 4. Track User Speech (STT Usage)
    client.TrackVoiceSTT(sessionID, map[string]interface{}{
        "serviceProvider": paygent.Deepgram,
        "model":           paygent.DeepgramNova2,
        "audioDuration":   5.0, // duration in minutes (e.g. 300 seconds → 5.0)
    })

    // 5. Track AI Processing (LLM Usage)
    client.TrackVoiceLLM(sessionID, map[string]interface{}{
        "serviceProvider":  paygent.OpenAI,
        "model":            paygent.GPT4O,
        "promptTokens":     1000,
        "completionTokens": 500,
    })

    // 6. Track AI Speech (TTS Usage)
    client.TrackVoiceTTS(sessionID, map[string]interface{}{
        "serviceProvider": paygent.DeepgramTTS,
        "model":           paygent.DeepgramAura2,
        "characterCount":  250,
    })

    // 7. Final Step: Set Indicator with Call Duration (Minutes)
    client.SetVoiceIndicator(sessionID, "voice_call_completed", 2.5)
}
```

## How it Works

### Step 1 — Customer Onboarding

The `CreateOrGetCustomer` call ensures the customer exists in Paygent. If they don't, we'll create them instantly using the provided `externalId`.

### Step 2 — Session Context

Initializing a voice session sets up a billing context for the call. This ensures all subsequent STT, LLM, and TTS usage is grouped under this single call session.

### Step 3 — Granular Tracking

Track every step of the voice pipeline independently. Paygent calculates precise costs for each model used during the conversation.

### Step 4 — Final Outcome

Finalize the session with `setVoiceIndicator`. Use the duration or outcome-based indicators to accurately bill your customers based on per-minute connectivity or success outcomes.