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

# Raya Voice AI best practices

Follow these best practices to get the most out of Raya Voice AI Agents API.

## Call Management

### Poll for Call Status

Check call status every 2 minutes until completion:

```python
import time

def poll_call_status(call_uuid, max_wait=600):
    start_time = time.time()
    while time.time() - start_time < max_wait:
        response = requests.get(
            f'https://v1.getraya.app/api/call/{call_uuid}',
            headers={'X-API-Key': 'your-api-key'}
        )
        status = response.json()
        
        if status['outcome'] in ['Completed', 'Failure']:
            return status
        
        time.sleep(120)  # Wait 2 minutes
    return None
```

### Handle Rate Limits

Implement exponential backoff for rate limit errors:

```python
import time

def make_call_with_retry(agent_id, phone_number, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = requests.post(
                'https://v1.getraya.app/api/call',
                headers={'X-API-Key': 'your-api-key'},
                json={
                    'agent_id': agent_id,
                    'to_number': phone_number,
                    'country_code': '91'
                }
            )
            
            if response.status_code == 200:
                return response.json()
            elif response.status_code == 429:
                # Rate limited
                wait_time = 60 * (attempt + 1)  # Wait 1, 2, 3 minutes
                time.sleep(wait_time)
                continue
            else:
                response.raise_for_status()
        except Exception as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)
    return None
```

## Batch Operations

### Use Batches for Scale

For multiple calls, always use batch operations instead of individual calls:

```python
# Good: Use batch
create_batch(agent_id, contacts)

# Bad: Multiple individual calls
for contact in contacts:
    make_call(agent_id, contact['phone'])
```

### Configure Appropriate Schedules

Set calling hours based on time zones and business hours:

```python
schedule = {
    'timezone': 'Asia/Kolkata',
    'start_time': '09:00',
    'end_time': '18:00',
    'days': [1, 2, 3, 4, 5]  # Monday to Friday
}
```

### Set Reasonable Concurrency

Don't set concurrency too high:

* Start with 1-2 concurrent calls
* Gradually increase based on account limits
* Monitor for rate limit errors

### Configure Retry Logic

Set appropriate retry settings:

* **Max retries**: 2-3 for most use cases
* **Retry after hours**: 3-24 hours depending on use case
* **Selected statuses**: Usually just `["Pending"]` for new contacts

## Agent Configuration

### Voice, language, and tools (API)

When setting `language_id` or `voice_id` on create/update:

* Use [Language Options](/voice-agents/language-options) and [Voice Options](/voice-agents/voice-options) for valid UUIDs. Your account may only support a subset.
* Do not guess UUIDs — invalid or disabled values return a `400` validation error.
* The language model is configured automatically on create; you cannot set or change it via the API.

For `tools`, send the full `{ "llm_tools": [...] }` payload you want stored. On PATCH, the `tools` key **replaces** the entire tool list — GET the agent first, merge changes, then PATCH.

For `voicemail_msg` and `call_duration_exceed_message`, use an empty string to clear a previously saved message.

### Write Clear Instructions

Provide detailed, specific instructions for agents:

* Be explicit about behavior
* Include examples
* Specify tone and style
* Define conversation flow

### Define Output Fields

Clearly specify what data to extract:

* Use descriptive field names
* Include format requirements
* Specify required vs optional fields

### Test Agents Thoroughly

Before deploying, test agents with:

* Various conversation scenarios
* Different user responses
* Edge cases
* Error handling

## Error Handling

### Validate Input

Always validate before making API calls:

```python
def validate_phone_number(phone):
    if not phone or len(phone) != 10:
        raise ValueError("Phone number must be 10 digits")
    if not phone.isdigit():
        raise ValueError("Phone number must contain only digits")
    return phone

def validate_agent_id(agent_id):
    # Validate UUID format
    import uuid
    try:
        uuid.UUID(agent_id)
    except ValueError:
        raise ValueError("Invalid agent ID format")
    return agent_id
```

### Handle All Error Cases

Check for all possible error scenarios:

* Validation errors (400)
* Authentication errors (401)
* Not found errors (404)
* Rate limit errors (429)
* Server errors (500)

## Security

### Store API Keys Securely

Never commit API keys to version control:

```python
import os

API_KEY = os.environ.get('RAYA_API_KEY')
if not API_KEY:
    raise ValueError("RAYA_API_KEY environment variable not set")
```

### Use Environment Variables

Store sensitive data in environment variables:

```bash
export RAYA_API_KEY="your-api-key"
```

## Monitoring

### Track Call Status

Monitor call outcomes:

* Success rates
* Failure reasons
* Average call duration
* Response times

### Log Important Events

Log key events for debugging:

* Call initiation
* Status changes
* Errors
* Webhook events

### Set Up Alerts

Configure alerts for:

* High failure rates
* Rate limit errors
* System errors
* Batch completion

## Performance Optimization

### Use Pagination

For large lists, use pagination:

```python
def get_all_agents():
    agents = []
    offset = 0
    limit = 100
    
    while True:
        response = requests.get(
            'https://v1.getraya.app/api/agent',
            headers={'X-API-Key': 'your-api-key'},
            params={'offset': offset, 'limit': limit}
        )
        data = response.json()
        agents.extend(data['agents'])
        
        if len(agents) >= data['total']:
            break
        offset += limit
    
    return agents
```

### Cache Agent Lists

Cache agent information to reduce API calls:

```python
agents_cache = {}
cache_time = 0

def get_agent(agent_id):
    if time.time() - cache_time > 3600:  # 1 hour
        # Refresh cache
        agents_cache = fetch_all_agents()
        cache_time = time.time()
    return agents_cache.get(agent_id)
```

## Webhook Best Practices

The payload your webhook receives is described in [Core Concepts — Webhooks](/voice-agents/core-concepts#webhooks). Webhooks are sent for both **completed** and **failed** calls; use the `outcome` field (`"Completed"` or `"Failure"`) to distinguish. The payload includes call metadata, transcript, recording URL, `agent_args` (object), and extracted `call_output` (populated mainly on completed calls).

### Verify Webhook Signatures

Always verify webhook authenticity:

```python
import hmac
import hashlib

def verify_webhook_signature(payload, signature, secret):
    expected_signature = hmac.new(
        secret.encode(),
        payload.encode(),
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(signature, expected_signature)
```

### Handle Webhook Failures

Implement retry logic for webhook delivery:

* Queue failed webhooks
* Retry with exponential backoff
* Log failures for manual review

## Testing

### Test in Staging

Always test in staging environment first:

* Test agent behavior
* Verify call flows
* Check error handling
* Validate data extraction

### Use Test Phone Numbers

Use test phone numbers for development:

* Avoid calling real customers during testing
* Use dedicated test numbers
* Verify behavior before production