# List All Batches Source: https://docs.dialgen.ai/api-reference/endpoint/batch-list get /api/v1/batch/list Retrieves a list of all call batches for the authenticated user, sorted by creation date (newest first). # Cancel Batch Source: https://docs.dialgen.ai/api-reference/endpoint/cancel-batch post /api/v1/batch/cancel Cancels a running or pending batch and removes all pending calls from the processing queue. # Persistent Call Status Source: https://docs.dialgen.ai/api-reference/endpoint/check-persistent-call-status get /api/v1/call/check-status Retrieves the status of a particular call from long-term storage. Use this endpoint after the call has been removed from the live memory cache (after 30 days). # Create a New Call Batch (Campaign) Source: https://docs.dialgen.ai/api-reference/endpoint/create-batch post /api/v1/batch Submits a list of contacts to be called as a new campaign. The server accepts the job and begins ingesting the contacts in the background. # Create Call Summary Source: https://docs.dialgen.ai/api-reference/endpoint/create-summary post /api/v1/call/create-summary Generates a summary and metrics for a completed call based on its transcription. This endpoint is idempotent; if a summary already exists, it will not be regenerated. # Start a Single Call Source: https://docs.dialgen.ai/api-reference/endpoint/dial-single post /api/v1/call/dial Initiates a single outbound call immediately. All endpoints should pass in the userId in the request body. # Get Agent Source: https://docs.dialgen.ai/api-reference/endpoint/get-agent get /api/v1/agent Retrieves the configuration and details for a specific AI agent. This includes basic information, active status, and metric configurations. # Get Batch Statistics (Overall Progress) Source: https://docs.dialgen.ai/api-reference/endpoint/get-batch-stats get /api/v1/batch/check-status Retrieves high-level statistics for a batch from persistent storage. This is a lightweight call to check the overall progress of your campaign. # Get Live Batch Status (Detailed) Source: https://docs.dialgen.ai/api-reference/endpoint/get-batch-status get /api/v1/status/batch Retrieves the live, individual status of every call within a batch from the memory cache (Redis). Data is available for 30 days. # Get Call Metrics Source: https://docs.dialgen.ai/api-reference/endpoint/get-call-metrics get /api/v1/call/get-metric Retrieves call metrics and analytics data after a call has completed. # Get Live Call Status Source: https://docs.dialgen.ai/api-reference/endpoint/get-call-status get /api/v1/status/call Retrieves the live status of an individual call from the memory cache (Redis). Data is available for 30 days. # API Introduction Source: https://docs.dialgen.ai/api-reference/introduction Welcome to the Dialgen API documentation. Our API allows you to programmatically initiate and monitor AI-powered voice calls, either one at a time or in high-volume batches. ## API Base URL All API endpoints are relative to the following base URL: ```bash theme={null} https://sa.dialgen.ai ``` ## OpenAPI Specification Our API is fully documented using the OpenAPI 3.0 specification. You can: * View the interactive API playground for each endpoint * Download the OpenAPI spec for use with API clients * Test endpoints directly from the documentation ### HTTP Methods Our API uses standard HTTP methods: * **GET** - Retrieve data (read operations) * **POST** - Create or modify data (write operations) Mintlify automatically displays color-coded indicators for each HTTP method on the endpoint pages. ## Authentication All API requests must be authenticated using a Bearer Token. Pass your API key in the `Authorization` header: ```bash theme={null} Authorization: Bearer ``` You can obtain your API key from the [Dialgen API Keys dashboard](https://sa.dialgen.ai/api-keys). **Important Note on `userId`** All endpoints should pass in the `userId` in the request body or query parameters. You can find your `userId` in the [sa.dialgen.ai](https://sa.dialgen.ai) dashboard. ## Response Formats The API uses standard HTTP status codes to indicate the success or failure of a request. All response bodies are returned in JSON format. | Status Code | Description | | :-------------------------- | :------------------------------------------------- | | `200 OK` | Request succeeded | | `202 Accepted` | Request accepted for processing (used for batches) | | `400 Bad Request` | Missing or invalid fields/parameters | | `401 Unauthorized` | Missing or invalid API key | | `402 Payment Required` | Insufficient call minutes/credits | | `404 Not Found` | The requested resource was not found | | `409 Conflict` | A call is already in progress for this contact | | `500 Internal Server Error` | An unexpected server error occurred | ## Best Practices ### Rate Limiting & Throttling * **Default Rate**: 10 calls per second (adjustable via `maxCallsPerSecond` in batch options). * **Recommendation**: Start with lower rates (5-10 CPS) and scale up based on your telephony provider's limits. ### Webhooks For a fully automated workflow, you can provide a webhook URL when creating a batch or initiating a call. * **Idempotency**: Your webhook endpoints should handle duplicate calls gracefully. * **Authentication**: Secure your webhook endpoints with authentication tokens. * **Timeout**: Respond to webhook calls within 5 seconds to avoid retries. * **Retry Logic**: We retry failed webhook calls up to 3 times with exponential backoff. # Changelog Source: https://docs.dialgen.ai/changelog Track changes and updates across Dialgen versions. This changelog provides a detailed overview of updates, new features, improvements, and bug fixes across different versions of Dialgen. ## Version 1.3.0 (February 2026) ### New Features * **Indian language support:** Voice agents can now speak and understand multiple Indian languages including Hindi, Tamil, Telugu, Bengali, Kannada, Malayalam, Marathi, Gujarati, Punjabi, Odia, and English India. To enable it, select **Dial6** in Voice Configuration and choose your desired language from the **Language** dropdown; the same dial also lets you pick the voice persona. * **Arabic language support:** Added support for Arabic (Saudi Arabia dialect). Voice agents can now understand and respond in Saudi Arabic. To enable it, select **Arabic** from the language dropdown and choose your preferred voice persona. ## Version 1.2.0 (December 30, 2025) ### API & Core Updates * **API Path Refactoring:** All private endpoints have been moved to the versioned `/api/v1/` path for consistency and future-proofing. * `/api/private/call/dial` → `/api/v1/call/dial` * `/api/private/call/get-metric` → `/api/v1/call/get-metric` * **Dual-Layer Status System:** Introduced a high-performance live status system using memory cache (Redis) with a 30-day retention period. * New endpoints for live tracking: `GET /api/v1/status/call` and `GET /api/v1/status/batch`. * **New Management Endpoints:** * **List All Batches:** `GET /api/v1/batch/list` – View all campaigns associated with your account. * **Create Call Summary:** `POST /api/v1/call/create-summary` – Manually trigger summary and metric generation. * **Cancel Batch:** `POST /api/v1/batch/cancel` – Stop running or pending campaigns immediately. * **System Health:** `GET /api/v1/health` – Monitor backend connectivity. * **Persistent Status:** Added `GET /api/v1/call/check-status` and `GET /api/v1/batch/check-status` for retrieving historical data after the 30-day live cache expires. * **Enhanced Batch Monitoring:** The `check-status` endpoint for batches now queries the database directly for accurate historical reporting and supports a `limit` parameter to control the number of recent calls returned. ### Improvements * **Auth Transparency:** Documentation now features highlighted `` callouts clearly explaining that `userId` should be passed in all requests. Added direct links to the [API Keys dashboard](https://sa.dialgen.ai/api-keys) for easier access. * **Documentation Revamp:** Updated all API reference pages to match the new versioned paths, added missing management endpoints, and enhanced monitoring workflows. ## Version 1.1.0 ### New Features * **Custom Voice Cloning (Enterprise):** Ability to upload voice samples for unique agent voices. * **Advanced Analytics Dashboard:** Enhanced metrics and visualization for call campaigns. ### Improvements * **Optimized Call Handling:** Improved stability and performance for high-volume batches. * **Webhook Reliability:** Enhanced retry mechanisms for webhook notifications. ### Bug Fixes * Resolved an issue with `maxCallsPerSecond` not applying correctly in certain scenarios. * Fixed minor display bugs in the dashboard's real-time call status. ## Version 1.0.0 (Initial Release) ### New Features * **Single Call Initiation:** Initial `POST /api/private/call/dial` endpoint. * **Batch Campaign Creation:** `POST /api/v1/batch` endpoint. * **Call Status Monitoring:** Initial monitoring endpoints. * **Batch Statistics:** `GET /api/v1/batch?batchId=`. * **Call Metrics Retrieval:** `GET /api/private/call/get-metric`. * **Agent Management:** Basic creation and configuration of AI agents. * **Dashboard:** Overview of active calls, lead conversions, and daily call duration. # Development Source: https://docs.dialgen.ai/development Preview changes locally to update your docs ## Hosted MCP Server Access your MCP server and preview available tools. ### MCP Server URL Use the following URL to connect AI applications to your documentation: `docs.dialgen.ai/mcp` ### Available Tools #### `SearchDialgen` Search across the Dialgen knowledge base to find relevant information, code examples, API references, and guides. Use this tool when you need to answer questions about Dialgen, find specific documentation, understand how features work, or locate implementation details. The search returns contextual content with titles and direct links to the documentation pages. # Dashboard Features Source: https://docs.dialgen.ai/essentials/dashboard-features Explore the key features and functionalities of the Dialgen dashboard. Welcome to the Dialgen Dashboard! This section provides an overview of the various features available to manage your AI agents, campaigns, and monitor call analytics. ## 📊 Dashboard Overview The main dashboard provides a quick glance at your operational metrics: * **Total Agents:** Number of active AI agents. * **Active Calls:** Real-time count of ongoing calls. * **Lead Conversions:** Track successful conversions from your campaigns. * **Daily Call Duration:** Aggregate duration of calls per day. * **Detailed Analytics:** Access in-depth transcription and sentiment analysis for each call. ## 🗣️ Voice Selection Dialgen offers a wide range of customizable voice options for your AI agents to ensure a natural and engaging conversation experience. * **Pre-built Voices:** Choose from a library of high-quality, human-like voices. * **Custom Voice Cloning:** (Enterprise Feature) Upload voice samples to create a unique, branded voice for your agents. * **Voice Parameters:** Adjust parameters such as: * **Pitch:** Control the highness or lowness of the voice. * **Speed:** Modify the speaking rate of the agent. * **Emotional Tone:** Fine-tune the sentiment (e.g., friendly, formal, empathetic). ## ⚙️ Advanced Settings The advanced settings section allows you to fine-tune your agents and campaigns for optimal performance. ### Agent Configuration * **System Prompts:** Define the core persona and guidelines for your AI agent. * **Agent Instructions:** Provide specific instructions for handling different scenarios during a call. * **Custom Metrics:** Configure custom metrics to track specific outcomes relevant to your business (e.g., `intent`, `sentiment`, `customerSatisfaction`). ### Campaign Settings * **Rate Limiting:** Control the `maxCallsPerSecond` to manage call volume. * **Retry Strategy:** Configure parameters for `maxAttempts`, `noAnswerDelay`, and `busyDelay` for failed calls. * **Webhooks:** Set up `onBatchComplete`, `onCallComplete`, and `onBatchFailed` webhooks for real-time notifications. * **Scheduling:** Schedule campaigns to start at a future `scheduledStartTime` with specified `timezone`. ### Security & Integrations * **API Key Management:** Generate and manage your API keys. * **Webhook Security:** Implement authentication tokens for secure webhook endpoints. * **CRM Integrations:** Connect Dialgen with your existing CRM systems for seamless data flow. # Batch Configuration Source: https://docs.dialgen.ai/guides/batch-calling/configuration Configure priority, rate limiting, scheduling, and retry strategies for your batch campaigns. ## Configuration Options Control how your batch campaign executes with these optional settings: ```json theme={null} { "options": { "priority": 5, "maxCallsPerSecond": 10, "scheduledStartTime": "2025-11-16T09:00:00.000Z", "timezone": "UTC", "retryStrategy": { "maxAttempts": 3, "noAnswerDelay": 3600000, "busyDelay": 300000 }, "webhooks": { "onBatchComplete": "https://api.your-crm.com/webhook/batch-complete", "onCallComplete": "https://api.your-crm.com/webhook/call-complete" }, "tags": ["Q4_campaign", "high_priority"] } } ``` *** ## Priority Set the priority level for your batch campaign: * **Range**: 1-10 * **Default**: 5 * **Behavior**: Higher priority batches are processed first ```json theme={null} { "priority": 8 } ``` Use higher priorities (7-10) for time-sensitive campaigns like appointment reminders or urgent notifications. *** ## Rate Limiting Control the number of calls initiated per second: * **Field**: `maxCallsPerSecond` * **Range**: 1-30 * **Default**: 10 ```json theme={null} { "maxCallsPerSecond": 15 } ``` ### Best Practices * **Start low**: Begin with 5-10 CPS and scale up * **Monitor quality**: Watch for connection issues * **Check limits**: Verify your telephony provider's limits * **Consider timezone**: Adjust rates for business hours Setting too high a rate may overwhelm your telephony provider or trigger spam filters. *** ## Scheduling Schedule your batch to start at a specific time: ```json theme={null} { "scheduledStartTime": "2025-11-16T09:00:00.000Z", "timezone": "America/New_York" } ``` ### Fields * **`scheduledStartTime`**: ISO 8601 datetime string * **`timezone`**: IANA timezone identifier * **Requirement**: Must be a future time ### Common Timezones * `America/New_York` - Eastern Time * `America/Chicago` - Central Time * `America/Los_Angeles` - Pacific Time * `Europe/London` - UK Time * `Asia/Tokyo` - Japan Time Schedule batches during business hours in your contacts' timezone for better answer rates. *** ## Retry Strategy Configure how failed calls are retried: ```json theme={null} { "retryStrategy": { "maxAttempts": 3, "noAnswerDelay": 3600000, "busyDelay": 300000 } } ``` ### Max Attempts * **Field**: `maxAttempts` * **Range**: 1-5 * **Default**: 3 Number of times to retry calling a contact. ### No Answer Delay * **Field**: `noAnswerDelay` * **Unit**: Milliseconds * **Default**: 3600000 (1 hour) Delay before retrying when call is not answered. ### Busy Delay * **Field**: `busyDelay` * **Unit**: Milliseconds * **Default**: 300000 (5 minutes) Delay before retrying when line is busy. ### Recommended Settings | Use Case | Max Attempts | No Answer Delay | Busy Delay | | ---------------------- | ------------ | --------------- | ---------- | | Urgent notifications | 2 | 30 min | 5 min | | Standard outreach | 3 | 1 hour | 15 min | | Low-priority campaigns | 2 | 4 hours | 30 min | *** ## Webhooks Receive HTTP notifications for batch events: ```json theme={null} { "webhooks": { "onBatchComplete": "https://api.your-crm.com/webhook/batch-complete", "onCallComplete": "https://api.your-crm.com/webhook/call-complete", "onBatchFailed": "https://api.your-crm.com/webhook/batch-failed" } } ``` ### Available Webhooks #### onBatchComplete Triggered when all calls in the batch are finished. ```json theme={null} { "event": "batch.completed", "batchId": "batch_123", "statistics": { "total": 1000, "succeeded": 850, "failed": 150 } } ``` #### onCallComplete Triggered after each individual call completes. ```json theme={null} { "event": "call.completed", "callId": "call_456", "status": "COMPLETED", "duration": 180, "summary": "Call summary text..." } ``` #### onBatchFailed Triggered if the batch fails to process. ```json theme={null} { "event": "batch.failed", "batchId": "batch_123", "error": "Insufficient credits" } ``` See the [Webhooks Guide](/guides/batch-calling/webhooks) for complete webhook documentation. *** ## Tags Add tags to organize and filter batches: ```json theme={null} { "tags": ["Q4_campaign", "high_priority", "lead_qualification"] } ``` ### Use Cases * **Campaign tracking**: Group related batches * **Filtering**: Find batches by category * **Reporting**: Analyze performance by tag * **Organization**: Manage multiple campaigns *** ## Complete Example ```json theme={null} { "agentId": "agent_123", "userId": "user_456", "contacts": [...], "options": { "priority": 7, "maxCallsPerSecond": 12, "scheduledStartTime": "2025-11-16T09:00:00.000Z", "timezone": "America/New_York", "retryStrategy": { "maxAttempts": 3, "noAnswerDelay": 3600000, "busyDelay": 300000 }, "webhooks": { "onBatchComplete": "https://api.yourcompany.com/webhooks/batch-complete", "onCallComplete": "https://api.yourcompany.com/webhooks/call-complete" }, "tags": ["Q4_2025", "lead_qualification", "high_value"] } } ``` *** ## Next Steps Track batch progress and performance Set up webhook notifications # Contact List Format Source: https://docs.dialgen.ai/guides/batch-calling/contact-format Structure your contact lists with phone numbers, names, and custom metadata. ## Contact Structure Each contact in your batch must include a phone number and can optionally include additional information: ```json theme={null} { "phoneNumber": "+15551234567", "name": "Jane Doe", "email": "jane@example.com", "company": "Acme Corp", "metadata": { "lead_score": 80, "account_id": "A123", "last_contact": "2025-01-15" } } ``` *** ## Required Fields ### Phone Number * **Field**: `phoneNumber` * **Format**: E.164 (e.g., `+15551234567`) * **Required**: Yes Phone numbers must include the country code and be in E.164 format. Invalid formats will be rejected. *** ## Optional Fields ### Name * **Field**: `name` * **Type**: String * **Default**: "Unknown" ```json theme={null} { "name": "Jane Doe" } ``` ### Email * **Field**: `email` * **Type**: String (valid email format) * **Default**: null ```json theme={null} { "email": "jane@example.com" } ``` ### Company * **Field**: `company` * **Type**: String * **Default**: null ```json theme={null} { "company": "Acme Corp" } ``` *** ## Custom Metadata Use the `metadata` field to pass custom variables to your agent: ```json theme={null} { "metadata": { "lead_score": 80, "account_id": "A123", "product_interest": "Enterprise Plan", "last_contact_date": "2025-01-15", "timezone": "America/New_York" } } ``` ### Using Metadata in Agent Prompts Reference metadata variables using curly braces: ```text theme={null} Hello {name}! I'm calling from Acme Corp regarding your interest in our {product_interest}. I see you're in the {timezone} timezone, so I wanted to reach out at a convenient time. Your account ID is {account_id} for reference. ``` Metadata is perfect for personalizing conversations and passing context-specific information to your agent. *** ## Contact Deduplication Dialgen automatically handles duplicate contacts: ### By Contact ID If you provide an existing `id`, the contact is reused: ```json theme={null} { "id": "contact_existing_123", "phoneNumber": "+15551234567", "name": "Jane Doe" } ``` ### By Phone Number Contacts with matching phone numbers are identified and reused: ```json theme={null} { "phoneNumber": "+15551234567" } ``` ### Benefits * **Preserves call history** across campaigns * **Prevents duplicates** in your database * **Resets attempt counts** for new campaigns * **Maintains contact data** integrity *** ## Example: Complete Contact List ```json theme={null} { "contacts": [ { "phoneNumber": "+15551234567", "name": "Jane Doe", "email": "jane@example.com", "company": "Acme Corp", "metadata": { "lead_score": 80, "account_id": "A123" } }, { "id": "contact_existing_456", "phoneNumber": "+15557654321", "name": "John Smith", "metadata": { "lead_score": 90, "follow_up": true } }, { "phoneNumber": "+15559876543", "name": "Alice Johnson" } ] } ``` *** ## Best Practices ### Validate Phone Numbers * Ensure all numbers are in E.164 format * Verify country codes are correct * Remove invalid or disconnected numbers ### Enrich Contact Data * Include names for personalization * Add email for follow-up communications * Use metadata for context-specific information ### Organize Metadata * Use consistent key names across contacts * Keep metadata relevant to the conversation * Avoid sensitive information in metadata ### Reuse Contact IDs * Provide existing contact IDs when available * Preserve call history across campaigns * Track contact interactions over time *** ## Next Steps Configure batch settings and options Complete API reference # CSV Upload Format Source: https://docs.dialgen.ai/guides/batch-calling/csv-format Learn how to format your CSV file for batch calling uploads. ## CSV File Format Your CSV file must follow these rules for successful batch calling: *** ## Rule 1: Use E.164 Phone Format All phone numbers must include the country prefix in E.164 format (e.g., `+11231237890`). **❌ Wrong:** ``` 1231237890 0091234567890 (123) 123-7890 ``` **✅ Correct:** ``` +11231237890 +919123456789 +44 2100000000 ``` E.164 is the international standard for phone numbers. It includes: * Plus sign (+) * Country code (1-3 digits) * Area code and number (up to 14 digits total) *** ## Rule 2: Use contact\_number Header The phone number column header must be exactly `contact_number`. **❌ Wrong:** ``` phone,name,email +11231237890,John,john@example.com ``` **✅ Correct:** ``` contact_number,name,email +11231237890,John,john@example.com ``` *** ## Rule 3: Add Custom Variables Include any additional variables (name, email, company, etc.) as separate columns. These are passed to your agent as context. **Example with custom variables:** ``` contact_number,first_name,last_name,company,email +11231237890,Bruce,Wayne,Wayne Enterprises,bruce@wayne.com +919123456789,Bruce,Lee,Martial Arts Inc,bruce@lee.com +00021000000,Satoshi,Nakamoto,Bitcoin,satoshi@nakamoto.com +44999999987,James,Bond,MI6,james@bond.com ``` *** ## Complete Example ```csv theme={null} contact_number,first_name,last_name,company,email +11231237890,John,Doe,Acme Corp,john@acme.com +12025550123,Jane,Smith,Tech Solutions,jane@tech.com +919876543210,Raj,Kumar,India Services,raj@india.com +441632960123,Alice,Johnson,UK Ventures,alice@uk.com +33123456789,Pierre,Dupont,France Consulting,pierre@france.com ``` *** ## Important Notes ### Excel Formula Warning In Excel, if you type a cell starting with `+`, it may be interpreted as a formula. To prevent this: 1. Right-click the column 2. Select **Format Cells** 3. Choose **Text** format 4. Add an apostrophe before the plus: `'+11231237890` The apostrophe won't appear in the final file, but it prevents Excel from treating it as a formula. ### Column Order * Column order doesn't matter * `contact_number` is the only required column * All other columns are optional and become variables ### Variable Naming * Use lowercase with underscores: `first_name`, `last_name`, `phone_ext` * Avoid spaces and special characters * Use clear, descriptive names *** ## Using Variables in Agent Prompts Reference variables in your agent prompt using curly braces: ```text theme={null} Hello {first_name}! I'm calling from {company} regarding your recent inquiry. I have your email on file as {email}. Is that still the best way to reach you? ``` *** ## Validation Checklist Before uploading, verify: * ✓ All phone numbers start with `+` * ✓ All phone numbers are in E.164 format * ✓ Header column is exactly `contact_number` * ✓ No duplicate phone numbers * ✓ No empty rows or columns * ✓ CSV is UTF-8 encoded * ✓ File size is under 50MB *** ## Common Issues ### "Invalid phone number format" **Problem:** Phone numbers not in E.164 format **Solution:** Add country code with `+` prefix ``` Before: 1234567890 After: +11234567890 ``` ### "contact\_number header not found" **Problem:** Column header is misspelled **Solution:** Make sure the header is exactly `contact_number` (lowercase, underscore) ``` Wrong: Contact Number, phone_number, Phone Right: contact_number ``` ### "Duplicate contact" **Problem:** Same phone number appears multiple times **Solution:** Remove duplicate rows or use different contact identifiers if needed *** ## Download Example Download our example CSV file to use as a template: ```csv theme={null} contact_number,first_name,last_name,company,email,lead_score +11231237890,Bruce,Wayne,Wayne Enterprises,bruce@wayne.com,95 +919123456789,Bruce,Lee,Martial Arts Inc,bruce@lee.com,85 +00021000000,Satoshi,Nakamoto,Bitcoin,satoshi@nakamoto.com,90 +44999999987,James,Bond,MI6,james@bond.com,80 ``` *** ## Next Steps JSON contact format for API calls API reference for batch creation # Monitoring Batches Source: https://docs.dialgen.ai/guides/batch-calling/monitoring Track batch progress, monitor call statuses, and analyze campaign performance. ## Batch Status Lifecycle Your batch progresses through these states: Contacts are being added to the database Waiting for scheduled start time Ready to start processing calls Actively making calls All calls finished *** ## Check Batch Status Get real-time status of your batch campaign: ```bash theme={null} curl --location 'https://sa.dialgen.ai/api/v1/status/batch?batchId=batch_123' \ --header 'Authorization: Bearer YOUR_API_KEY' ``` ### Response ```json theme={null} { "batchId": "batch_123", "calls": [ { "callId": "call_456", "status": "COMPLETED", "startTime": "2025-11-15T14:31:02.456Z", "phoneNumber": "+15551234567", "duration": 62, "recordingUrl": "https://..." }, { "callId": "call_789", "status": "ONGOING", "startTime": "2025-11-15T14:32:15.789Z", "phoneNumber": "+15557654321" } ] } ``` Live batch status is available for 30 days. After that, use the [Batch Statistics API](/api-reference/endpoint/get-batch-stats). *** ## Get Batch Statistics Retrieve high-level statistics for your campaign: ```bash theme={null} curl --location 'https://sa.dialgen.ai/api/v1/batch/check-status?batchId=batch_123&limit=20' \ --header 'Authorization: Bearer YOUR_API_KEY' ``` ### Response ```json theme={null} { "batchId": "batch_123", "status": "processing", "priority": 5, "statistics": { "total": 1000, "processed": 500, "succeeded": 450, "failed": 50, "pending": 500, "percentComplete": 50, "successRate": 90 }, "performance": { "callsPerSecond": 10.5, "estimatedTimeRemaining": 3600, "elapsedTime": 1800 }, "timestamps": { "createdAt": "2025-11-15T14:00:00.000Z", "startedAt": "2025-11-15T14:05:00.000Z", "completedAt": null } } ``` *** ## List All Batches Get a list of all your batch campaigns: ```bash theme={null} curl --location 'https://sa.dialgen.ai/api/v1/batch/list' \ --header 'Authorization: Bearer YOUR_API_KEY' ``` ### Response ```json theme={null} [ { "batchId": "batch_123", "status": "processing", "total": 1000, "processed": 500, "succeeded": 450, "failed": 50, "percentComplete": 50, "createdAt": "2025-11-15T14:00:00.000Z", "agentId": "agent_abc", "priority": 5 } ] ``` *** ## Key Metrics ### Statistics | Metric | Description | | ----------------- | --------------------------------- | | `total` | Total number of contacts in batch | | `processed` | Number of calls attempted | | `succeeded` | Number of successful calls | | `failed` | Number of failed calls | | `pending` | Number of calls not yet attempted | | `percentComplete` | Percentage of batch completed | | `successRate` | Percentage of successful calls | ### Performance | Metric | Description | | ------------------------ | ---------------------------------- | | `callsPerSecond` | Current call rate | | `estimatedTimeRemaining` | Estimated seconds until completion | | `elapsedTime` | Seconds since batch started | *** ## Call Statuses Individual calls can have these statuses: | Status | Description | | ----------- | ------------------------------------------ | | `SCHEDULED` | Call is queued and waiting to be initiated | | `ONGOING` | Call is currently in progress | | `COMPLETED` | Call finished successfully | | `MISSED` | Call was not answered | | `FAILED` | Call failed due to technical error | *** ## Monitoring Best Practices ### Poll Regularly Check batch status every 30-60 seconds during processing: ```javascript theme={null} async function monitorBatch(batchId) { let status = 'processing'; while (status === 'processing' || status === 'pending') { const response = await fetch( `https://sa.dialgen.ai/api/v1/batch/check-status?batchId=${batchId}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const data = await response.json(); status = data.status; console.log(`Progress: ${data.statistics.percentComplete}%`); if (status !== 'completed') { await new Promise(resolve => setTimeout(resolve, 30000)); // Wait 30s } } console.log('Batch completed!'); } ``` ### Use Webhooks Instead of polling, use webhooks for real-time notifications: ```json theme={null} { "webhooks": { "onCallComplete": "https://api.yourcompany.com/webhooks/call-complete", "onBatchComplete": "https://api.yourcompany.com/webhooks/batch-complete" } } ``` ### Track Key Metrics Monitor these metrics for campaign health: * **Success Rate**: Should be > 70% * **Average Duration**: Indicates conversation quality * **Calls Per Second**: Verify rate limiting is working * **Failed Calls**: Investigate if > 20% *** ## Dashboard Monitoring View batch progress in the Dialgen dashboard: 1. Navigate to **Batches** 2. Click on your batch campaign 3. View real-time statistics and call list 4. Filter calls by status 5. Download reports and transcripts *** ## Troubleshooting ### Low Success Rate **Problem**: Success rate \< 50% **Solutions**: * Check phone number quality * Verify calling hours match timezone * Review agent prompt effectiveness * Adjust retry strategy ### Slow Processing **Problem**: Batch taking longer than expected **Solutions**: * Increase `maxCallsPerSecond` * Check telephony provider limits * Verify agent is active * Review system status ### High Failure Rate **Problem**: Many calls failing **Solutions**: * Validate phone number format * Check API key permissions * Verify agent configuration * Review error messages in call details *** ## Next Steps Set up real-time notifications Analyze individual call performance # Batch Calling Overview Source: https://docs.dialgen.ai/guides/batch-calling/overview Automate outbound calls to hundreds or thousands of contacts with batch campaigns. ## What is Batch Calling? Batch calling lets you automate outbound calls to hundreds or thousands of contacts by uploading a list of contacts. Ideal for lead qualification, customer outreach, appointment reminders, and other high-volume calling campaigns. *** ## Key Features Upload and manage contact lists with custom metadata Configure priority, rate limiting, scheduling, and retry strategies Track batch progress and individual call statuses in real-time Receive notifications for batch and call completion events *** ## How It Works Configure your AI agent with voice settings, prompt, and metrics Submit your contact list via API with phone numbers and metadata Set priority, rate limits, scheduling, and retry strategies Track batch status and individual call progress in real-time Get detailed metrics, transcripts, and summaries for each call *** ## Quick Start Create a batch campaign with a simple API call: ```bash theme={null} curl --location 'https://sa.dialgen.ai/api/v1/batch' \ --header 'Authorization: Bearer YOUR_API_KEY' \ --header 'Content-Type: application/json' \ --data '{ "agentId": "agent_123", "userId": "user_456", "contacts": [ { "phoneNumber": "+15551234567", "name": "Jane Doe", "email": "jane@example.com" } ] }' ``` See the [Create Batch API](/api-reference/endpoint/create-batch) for complete documentation. *** ## Use Cases ### Lead Qualification Automatically call leads to qualify interest and gather information. ### Customer Outreach Reach out to customers for feedback, surveys, or announcements. ### Appointment Reminders Send automated appointment reminders to reduce no-shows. ### Follow-ups Follow up with customers after purchases or support interactions. *** ## Next Steps Learn about contact list structure and metadata Explore all batch configuration settings Track and analyze batch campaign performance Complete API documentation for batch calling # Batch Webhooks Source: https://docs.dialgen.ai/guides/batch-calling/webhooks Receive real-time notifications for batch and call completion events. ## What are Webhooks? Webhooks are HTTP callbacks that Dialgen sends to your server when specific events occur. Instead of polling for updates, your application receives instant notifications. *** ## Available Webhooks ### onBatchComplete Triggered when all calls in the batch are finished. ```json theme={null} { "event": "batch.completed", "batchId": "batch_123", "agentId": "agent_456", "userId": "user_789", "statistics": { "total": 1000, "processed": 1000, "succeeded": 850, "failed": 150, "percentComplete": 100, "successRate": 85 }, "timestamps": { "createdAt": "2025-11-15T14:00:00.000Z", "startedAt": "2025-11-15T14:05:00.000Z", "completedAt": "2025-11-15T16:30:00.000Z" } } ``` ### onCallComplete Triggered after each individual call completes. Includes full call data: ```json theme={null} { "success": true, "callData": { "id": "call_123", "contactId": "contact_456", "agentId": "agent_789", "batchId": "batch_abc", "status": "COMPLETED", "startTime": "2025-11-15T14:30:00.000Z", "endTime": "2025-11-15T14:33:00.000Z", "duration": 180, "phoneNumber": "+1234567890", "contactName": "John Doe", "transcription": [...], "recordingUrl": "https://...", "summary": "Call summary text...", "metricJson": { "intent": "SALES_INQUIRY", "sentiment": "positive", "confidence": 0.95 } }, "metricSchema": {...} } ``` ### onBatchFailed Triggered if the batch fails to process: ```json theme={null} { "event": "batch.failed", "batchId": "batch_123", "agentId": "agent_456", "error": "Insufficient call minutes", "code": "INSUFFICIENT_CREDITS", "timestamp": "2025-11-15T14:05:00.000Z" } ``` *** ## Configuring Webhooks Add webhook URLs when creating your batch: ```json theme={null} { "agentId": "agent_123", "userId": "user_456", "contacts": [...], "options": { "webhooks": { "onBatchComplete": "https://api.yourcompany.com/webhooks/batch-complete", "onCallComplete": "https://api.yourcompany.com/webhooks/call-complete", "onBatchFailed": "https://api.yourcompany.com/webhooks/batch-failed" } } } ``` *** ## Implementing Webhook Endpoints ### Node.js Example ```javascript theme={null} const express = require('express'); const app = express(); app.use(express.json()); // Handle call completion app.post('/webhooks/call-complete', (req, res) => { const { callData } = req.body; console.log(`Call ${callData.id} completed`); console.log(`Duration: ${callData.duration}s`); console.log(`Summary: ${callData.summary}`); // Process call data // - Update CRM // - Send notifications // - Trigger workflows res.status(200).json({ received: true }); }); // Handle batch completion app.post('/webhooks/batch-complete', (req, res) => { const { batchId, statistics } = req.body; console.log(`Batch ${batchId} completed`); console.log(`Success rate: ${statistics.successRate}%`); // Process batch completion // - Generate reports // - Send summary email // - Archive batch data res.status(200).json({ received: true }); }); app.listen(3000); ``` ### Python Example ```python theme={null} from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/webhooks/call-complete', methods=['POST']) def call_complete(): data = request.json call_data = data['callData'] print(f"Call {call_data['id']} completed") print(f"Duration: {call_data['duration']}s") print(f"Summary: {call_data['summary']}") # Process call data # - Update CRM # - Send notifications # - Trigger workflows return jsonify({'received': True}), 200 @app.route('/webhooks/batch-complete', methods=['POST']) def batch_complete(): data = request.json batch_id = data['batchId'] statistics = data['statistics'] print(f"Batch {batch_id} completed") print(f"Success rate: {statistics['successRate']}%") # Process batch completion # - Generate reports # - Send summary email # - Archive batch data return jsonify({'received': True}), 200 if __name__ == '__main__': app.run(port=3000) ``` *** ## Best Practices ### Respond Quickly * Respond within 5 seconds to avoid retries * Return a 2xx status code immediately * Process data asynchronously if needed ```javascript theme={null} app.post('/webhooks/call-complete', async (req, res) => { // Respond immediately res.status(200).json({ received: true }); // Process asynchronously processCallData(req.body).catch(console.error); }); ``` ### Handle Idempotency Webhooks may be delivered multiple times. Use idempotency keys: ```javascript theme={null} const processedWebhooks = new Set(); app.post('/webhooks/call-complete', (req, res) => { const callId = req.body.callData.id; if (processedWebhooks.has(callId)) { return res.status(200).json({ received: true, duplicate: true }); } processedWebhooks.add(callId); // Process webhook processCallData(req.body); res.status(200).json({ received: true }); }); ``` ### Secure Your Endpoints Verify webhook authenticity: ```javascript theme={null} const crypto = require('crypto'); function verifyWebhook(req, secret) { const signature = req.headers['x-dialgen-signature']; const payload = JSON.stringify(req.body); const expectedSignature = crypto .createHmac('sha256', secret) .update(payload) .digest('hex'); return signature === expectedSignature; } app.post('/webhooks/call-complete', (req, res) => { if (!verifyWebhook(req, process.env.WEBHOOK_SECRET)) { return res.status(401).json({ error: 'Invalid signature' }); } // Process webhook res.status(200).json({ received: true }); }); ``` ### Log Everything Keep detailed logs for debugging: ```javascript theme={null} app.post('/webhooks/call-complete', (req, res) => { console.log('Webhook received:', { timestamp: new Date().toISOString(), callId: req.body.callData?.id, status: req.body.callData?.status, headers: req.headers }); // Process webhook res.status(200).json({ received: true }); }); ``` ### Handle Errors Gracefully ```javascript theme={null} app.post('/webhooks/call-complete', async (req, res) => { try { await processCallData(req.body); res.status(200).json({ received: true }); } catch (error) { console.error('Webhook processing error:', error); // Still return 200 to prevent retries for application errors res.status(200).json({ received: true, error: error.message }); } }); ``` *** ## Retry Logic If your endpoint fails, Dialgen will retry: * **Retry Attempts**: Up to 3 times * **Retry Delay**: Exponential backoff (1s, 5s, 25s) * **Timeout**: 30 seconds per attempt If all retries fail, the webhook is dropped. Implement proper error handling and logging. *** ## Testing Webhooks ### Use ngrok for Local Testing ```bash theme={null} # Start ngrok ngrok http 3000 # Use the ngrok URL in your webhook configuration https://abc123.ngrok.io/webhooks/call-complete ``` ### Test with curl ```bash theme={null} curl -X POST https://your-server.com/webhooks/call-complete \ -H "Content-Type: application/json" \ -d '{ "success": true, "callData": { "id": "call_test_123", "status": "COMPLETED", "duration": 180 } }' ``` *** ## Common Use Cases ### Update CRM ```javascript theme={null} app.post('/webhooks/call-complete', async (req, res) => { const { callData } = req.body; await crm.updateContact({ id: callData.contactId, lastCallDate: callData.startTime, callSummary: callData.summary, sentiment: callData.metricJson.sentiment }); res.status(200).json({ received: true }); }); ``` ### Send Notifications ```javascript theme={null} app.post('/webhooks/batch-complete', async (req, res) => { const { batchId, statistics } = req.body; await sendEmail({ to: 'team@company.com', subject: `Batch ${batchId} Completed`, body: ` Total Calls: ${statistics.total} Success Rate: ${statistics.successRate}% Succeeded: ${statistics.succeeded} Failed: ${statistics.failed} ` }); res.status(200).json({ received: true }); }); ``` ### Trigger Workflows ```javascript theme={null} app.post('/webhooks/call-complete', async (req, res) => { const { callData } = req.body; if (callData.metricJson.intent === 'INTERESTED') { await workflow.trigger('send-follow-up-email', { contactId: callData.contactId, summary: callData.summary }); } res.status(200).json({ received: true }); }); ``` *** ## Next Steps Track batch progress and performance Retrieve detailed call metrics # Call Status Source: https://docs.dialgen.ai/guides/call-management/call-status Monitor call status, lifecycle, and completion states. ## Call Status Types Calls progress through these statuses: | Status | Description | | ----------- | ------------------------------------------ | | `SCHEDULED` | Call is queued and waiting to be initiated | | `ONGOING` | Call is currently in progress | | `COMPLETED` | Call finished successfully | | `MISSED` | Call was not answered | | `FAILED` | Call failed due to technical error | *** ## Checking Call Status ### Live Status (30 Days) For recent calls, use the live status endpoint: ```bash theme={null} curl --location 'https://sa.dialgen.ai/api/v1/status/call?callId=call_123' \ --header 'Authorization: Bearer YOUR_API_KEY' ``` **Response:** ```json theme={null} { "callId": "call_123", "status": "ONGOING", "startTime": "2025-11-15T14:30:01.123Z", "phoneNumber": "+15551234567", "contactId": "contact_456", "batchId": null, "error": null, "duration": null, "recordingUrl": null } ``` ### Persistent Status (After 30 Days) For older calls, use the persistent status endpoint: ```bash theme={null} curl --location 'https://sa.dialgen.ai/api/v1/call/check-status?callId=call_123' \ --header 'Authorization: Bearer YOUR_API_KEY' ``` Live status is cached for 30 days. After that, use the persistent status endpoint for historical data. *** ## Call Lifecycle Call is queued in the system Call is connected and conversation is active Call has ended with a final status *** ## Status Details ### SCHEDULED * Call is in queue * Waiting to be initiated * Can be cancelled ### ONGOING * Call is connected * Conversation in progress * Real-time transcription active * Duration counter running ### COMPLETED * Call ended successfully * Recording available * Transcript available * Metrics generated * Summary created ### MISSED * Call was not answered * Will retry based on retry strategy * No recording or transcript ### FAILED * Technical error occurred * Error message available * May retry based on error type *** ## Monitoring Active Calls Track ongoing calls in real-time: ```javascript theme={null} async function monitorCall(callId) { let status = 'ONGOING'; while (status === 'ONGOING' || status === 'SCHEDULED') { const response = await fetch( `https://sa.dialgen.ai/api/v1/status/call?callId=${callId}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY' } } ); const data = await response.json(); status = data.status; if (data.duration) { console.log(`Call duration: ${data.duration}s`); } if (status === 'ONGOING') { await new Promise(resolve => setTimeout(resolve, 5000)); // Wait 5s } } console.log(`Call ended with status: ${status}`); } ``` *** ## Error Handling ### Common Error Codes | Error Code | Description | | ---------------------- | -------------------------------- | | `INVALID_NUMBER` | Phone number is invalid | | `BUSY` | Line is busy | | `NO_ANSWER` | Call was not answered | | `NETWORK_ERROR` | Network connectivity issue | | `INSUFFICIENT_CREDITS` | Not enough credits to place call | ### Retry Behavior * **BUSY**: Retries after `busyDelay` * **NO\_ANSWER**: Retries after `noAnswerDelay` * **Other errors**: May not retry depending on error type *** ## Webhooks for Status Updates Receive real-time status updates via webhooks: ```json theme={null} { "webhooks": { "onCallComplete": "https://api.yourcompany.com/webhooks/call-complete" } } ``` ### Webhook Payload ```json theme={null} { "event": "call.completed", "callId": "call_123", "status": "COMPLETED", "duration": 180, "contactId": "contact_456", "summary": "Call summary...", "recordingUrl": "https://..." } ``` *** ## Next Steps Get detailed call metrics and analytics Access call recordings and transcripts # Call Duration Limits Source: https://docs.dialgen.ai/guides/call-management/duration-limits Set maximum call duration to automatically terminate calls and manage resources. ## What are Duration Limits? Duration limits set a maximum length (in seconds) for calls. Once reached, the call automatically terminates. *** ## Why Use Duration Limits? Prevent unexpectedly long calls from consuming excessive credits Ensure fair allocation of concurrent call capacity Protect against technical issues that prevent natural endings Better forecast and manage calling expenses *** ## Configuration Set the maximum duration in your agent settings: ```json theme={null} { "maxCallDuration": 900 } ``` * **Unit**: Seconds * **Default**: 1800 (30 minutes) * **Recommended**: 300-1800 based on use case *** ## Recommended Durations | Use Case | Duration | Seconds | | ------------------ | -------- | ------- | | Quick inquiries | 5 min | 300 | | Lead qualification | 10 min | 600 | | Customer support | 15 min | 900 | | Sales calls | 20 min | 1200 | | Consultations | 30 min | 1800 | *** ## What Happens at Limit? When the duration limit is reached: 1. Call terminates immediately 2. Hangup message is played (if configured) 3. Status updates to `COMPLETED` 4. Recording and transcript are saved 5. Metrics are generated 6. Webhooks are triggered The call ends immediately when the limit is reached, even mid-sentence. Consider adding a warning before the limit. *** ## Best Practices ### Set Realistic Limits * Analyze average call durations * Set limits 20-30% above average * Account for edge cases ### Add Warning Messages Include a prompt to warn users: ```text theme={null} DURATION WARNING: - When 80% of max duration is reached, say: "We have about 2 minutes left. Is there anything else I can help you with?" - When 95% is reached, say: "We're almost out of time. Let me quickly address your main concern." ``` ### Monitor Metrics Track: * Calls hitting duration limit * Average duration by use case * Correlation with satisfaction scores *** ## Next Steps Configure natural call endings Monitor call status and metrics # Hangup Detection Source: https://docs.dialgen.ai/guides/call-management/hangup-detection Configure silence detection and custom prompts for natural call endings. ## Hangup Methods Dialgen offers two methods for intelligent call termination: *** ## Silence Detection Automatically end calls when no audio is detected: ```json theme={null} { "silenceTimeout": 12 } ``` * **Unit**: Seconds * **Default**: 10 * **Recommended**: 8-15 seconds ### How It Works 1. Timer starts when agent finishes speaking 2. Timer resets if user speaks 3. If timer reaches threshold, call ends 4. Hangup message plays (if configured) 5. Call terminates ### Recommended Timeouts | Use Case | Timeout | | --------------------- | ------- | | Quick inquiries | 8-10s | | Standard support | 10-15s | | Complex consultations | 15-20s | Too short may disconnect during natural pauses. Too long wastes time and credits. *** ## Prompt-Based Detection Add hangup logic to your agent prompt: ```text theme={null} HANGUP RULES: - End the call when the customer says "goodbye," "that's all," or "thank you, bye" - End when the customer confirms their issue is resolved - End when the customer says they have no more questions - Always thank the customer before ending ``` ### Example Prompt ```text theme={null} You are a customer support agent for Acme Corp. Your goal is to help customers and resolve their issues. HANGUP DETECTION: A conversation is complete when: 1. The customer explicitly says they want to end the call 2. The customer confirms their issue is fully resolved 3. The customer says they have no further questions When ending the call: - Thank the customer for calling - Confirm their issue is resolved - Offer to help again in the future - Say goodbye warmly ``` Prompt-based detection relies on AI interpretation and may not be 100% accurate. Test thoroughly. *** ## Hangup Messages Configure a custom closing message: ```json theme={null} { "hangupMessage": "Thank you for calling Acme Corp, {name}. Have a wonderful day!" } ``` ### Available Variables * `{name}` - Contact's name * `{company}` - Contact's company * `{email}` - Contact's email * Any custom metadata variables ### Examples **Professional:** ```text theme={null} Thank you for your time, {name}. If you need further assistance, please don't hesitate to call us back. ``` **Friendly:** ```text theme={null} Thanks so much for chatting with me today, {name}! Have an awesome day! ``` **Multilingual (Spanish):** ```text theme={null} Gracias por llamar, {name}. ¡Que tenga un excelente día! ``` *** ## Combining Methods Use both silence detection and prompt-based hangup: ```json theme={null} { "silenceTimeout": 12, "hangupMessage": "Thank you for calling, {name}!" } ``` ```text theme={null} HANGUP RULES: - End when customer says goodbye or confirms they're done - End when issue is fully resolved - If there's silence for more than 10 seconds, ask: "Are you still there? Is there anything else I can help with?" ``` ### Benefits * **Silence detection**: Catches abandoned calls * **Prompt-based**: Natural, context-aware endings * **Hangup message**: Professional closing *** ## Hangup Status Codes Track why calls ended: | Status | Description | | ------------- | ---------------------------- | | `COMPLETED` | Call ended normally | | `USER_HANGUP` | User hung up | | `SILENCE` | Ended due to silence timeout | | `TIMEOUT` | Reached maximum duration | | `FAILED` | Technical error | Status codes are available in call metrics and webhook payloads. *** ## Troubleshooting ### Calls Ending Too Early **Solutions:** * Increase silence timeout to 15-20 seconds * Make hangup conditions more specific * Review call recordings ### Calls Running Too Long **Solutions:** * Decrease silence timeout to 8-10 seconds * Add explicit hangup conditions to prompt * Implement duration limits *** ## Next Steps Set maximum call duration Monitor call status and lifecycle # Call Management Source: https://docs.dialgen.ai/guides/call-management/overview Configure call duration limits, hangup detection, and call termination settings. ## Managing Call Lifecycle Control how calls start, progress, and end with Dialgen's call management features. *** ## Features Set maximum call duration as a safety net Configure silence detection and natural call endings Monitor call status and lifecycle Access call recordings and transcripts *** ## Call Lifecycle Call is queued and waiting to be placed Phone is ringing, waiting for answer Call is answered and conversation begins Conversation in progress Hangup detected or duration limit reached Call ended, recording and metrics saved *** ## Key Settings ### Duration Limits Set maximum call length to prevent runaway calls: ```json theme={null} { "maxCallDuration": 900 } ``` ### Silence Detection Configure silence timeout for automatic hangup: ```json theme={null} { "silenceTimeout": 12 } ``` ### Hangup Message Customize the closing message: ```json theme={null} { "hangupMessage": "Thank you for calling, {name}. Have a great day!" } ``` *** ## Best Practices ### Combine Multiple Methods Use both duration limits and hangup detection: * **Duration limits**: Safety net (hard cutoff) * **Hangup detection**: Natural endings (intelligent) ### Monitor Call Metrics Track these metrics: * Average call duration * Hangup reasons * Success rate * User satisfaction ### Test Thoroughly * Test various conversation flows * Monitor premature hangups * Adjust settings based on data *** ## Next Steps Configure maximum call duration Set up intelligent call termination # Recordings & Transcripts Source: https://docs.dialgen.ai/guides/call-management/recordings Access call recordings, transcripts, and conversation data. ## Call Recordings Every call is automatically recorded and stored securely. *** ## Accessing Recordings ### Via API Get the recording URL from call metrics: ```bash theme={null} curl --location 'https://sa.dialgen.ai/api/v1/call/get-metric?callId=call_123&userId=user_456&agentId=agent_789&contactId=contact_123' \ --header 'Authorization: Bearer YOUR_API_KEY' ``` **Response:** ```json theme={null} { "success": true, "callData": { "id": "call_123", "recordingUrl": "https://recordings.dialgen.ai/call_123.mp3", "duration": 180 } } ``` ### Via Webhook Receive recording URL in the `onCallComplete` webhook: ```json theme={null} { "callData": { "recordingUrl": "https://recordings.dialgen.ai/call_123.mp3" } } ``` *** ## Transcripts Full conversation transcripts are available for every call. ### Transcript Format ```json theme={null} { "transcription": [ { "role": "assistant", "content": "Hello! Thank you for calling Acme Corp. How can I help you today?", "timestamp": "2025-11-15T14:30:02.000Z" }, { "role": "user", "content": "Hi, I'm interested in your pricing plans.", "timestamp": "2025-11-15T14:30:05.000Z" }, { "role": "assistant", "content": "Great! We have three plans available...", "timestamp": "2025-11-15T14:30:08.000Z" } ] } ``` ### Transcript Fields * **`role`**: `assistant` (agent) or `user` (caller) * **`content`**: The spoken text * **`timestamp`**: When the message was spoken *** ## Storage & Retention ### Recording Storage * **Format**: MP3 * **Quality**: High-quality audio * **Retention**: 90 days * **Access**: Via secure HTTPS URLs ### Transcript Storage * **Format**: JSON * **Retention**: Permanent * **Access**: Via API Recordings are automatically deleted after 90 days. Download and store recordings externally if you need longer retention. *** ## Downloading Recordings ### Single Recording ```javascript theme={null} async function downloadRecording(recordingUrl, callId) { const response = await fetch(recordingUrl); const buffer = await response.arrayBuffer(); // Save to file const fs = require('fs'); fs.writeFileSync(`recording_${callId}.mp3`, Buffer.from(buffer)); } ``` ### Batch Download ```javascript theme={null} async function downloadBatchRecordings(batchId) { const calls = await getBatchCalls(batchId); for (const call of calls) { if (call.recordingUrl) { await downloadRecording(call.recordingUrl, call.id); } } } ``` *** ## Privacy & Compliance ### Data Security * All recordings are encrypted at rest * Secure HTTPS URLs with expiration * Access controlled by API authentication ### Compliance * **GDPR**: Right to deletion supported * **CCPA**: Data access and deletion available * **Recording Disclosure**: Ensure proper call recording disclosures Always inform callers that the call is being recorded, as required by law in many jurisdictions. *** ## Using Transcripts ### Search Transcripts ```javascript theme={null} function searchTranscript(transcript, keyword) { return transcript.filter(message => message.content.toLowerCase().includes(keyword.toLowerCase()) ); } // Find mentions of "pricing" const pricingMentions = searchTranscript(transcript, 'pricing'); ``` ### Analyze Sentiment ```javascript theme={null} function analyzeSentiment(transcript) { const userMessages = transcript.filter(m => m.role === 'user'); // Use sentiment analysis on user messages const sentiments = userMessages.map(msg => analyzeSentiment(msg.content) ); return averageSentiment(sentiments); } ``` ### Extract Key Information ```javascript theme={null} function extractPhoneNumbers(transcript) { const phoneRegex = /\+?\d{10,}/g; const allText = transcript.map(m => m.content).join(' '); return allText.match(phoneRegex) || []; } ``` *** ## Best Practices ### Inform Callers Add a disclosure to your agent prompt: ```text theme={null} OPENING MESSAGE: "Hello! This call may be recorded for quality and training purposes. How can I help you today?" ``` ### Store Securely * Download recordings to secure storage * Encrypt stored recordings * Implement access controls * Set retention policies ### Analyze Regularly * Review transcripts for quality * Identify common issues * Train agents based on insights * Improve prompts based on patterns *** ## Next Steps Get detailed call analytics Configure call termination settings # API Integration Source: https://docs.dialgen.ai/guides/custom-functions/api-integration Connect external APIs to your Dialgen AI agents with custom functions. ## Function Definition Structure A complete function definition includes: ```json theme={null} { "name": "function_name", "description": "Clear description of what this function does and when to use it", "parameters": { "type": "object", "properties": { "param1": { "type": "string", "description": "Parameter description" } }, "required": ["param1"] }, "api_endpoint": "https://api.yourcompany.com/endpoint", "http_method": "POST", "headers": { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" }, "body_template": { "field": "{{param1}}" } } ``` *** ## Components ### Name * Use snake\_case * Be descriptive but concise * Unique within agent ```json theme={null} { "name": "check_order_status" } ``` ### Description The most important part. Be specific about: * What the function does * When to call it * What triggers it **❌ Bad:** ```json theme={null} { "description": "Gets data" } ``` **✅ Good:** ```json theme={null} { "description": "Retrieves the customer's order status including tracking information and estimated delivery date. Call this when the customer asks about their order, delivery, shipping, or tracking." } ``` ### Parameters Define using JSON Schema: ```json theme={null} { "parameters": { "type": "object", "properties": { "order_id": { "type": "string", "description": "The order number or ID" }, "email": { "type": "string", "format": "email", "description": "Customer's email for verification" } }, "required": ["order_id"] } } ``` ### API Endpoint Your API URL to call: ```json theme={null} { "api_endpoint": "https://api.yourcompany.com/orders/status" } ``` ### HTTP Method ```json theme={null} { "http_method": "POST" } ``` Options: `GET`, `POST`, `PUT`, `PATCH`, `DELETE` ### Headers Authentication and content type: ```json theme={null} { "headers": { "Authorization": "Bearer {{API_KEY}}", "Content-Type": "application/json", "X-Custom-Header": "value" } } ``` ### Body Template Map parameters to API request body: ```json theme={null} { "body_template": { "order_id": "{{order_id}}", "customer_email": "{{email}}", "source": "ai_agent" } } ``` *** ## Context Variables Use these built-in variables: | Variable | Description | | ------------------ | ------------------------- | | `{{agent_id}}` | Current agent ID | | `{{call_sid}}` | Unique call ID | | `{{from_number}}` | Caller's phone number | | `{{to_number}}` | Called phone number | | `{{contact_id}}` | Contact ID (if available) | | `{{contact_name}}` | Contact name | Plus any custom variables from contact metadata. *** ## Parameter Types ### String ```json theme={null} { "name": { "type": "string", "description": "Customer's full name" } } ``` ### Number ```json theme={null} { "quantity": { "type": "number", "minimum": 1, "maximum": 100, "description": "Quantity to order" } } ``` ### Boolean ```json theme={null} { "send_confirmation": { "type": "boolean", "description": "Whether to send email confirmation" } } ``` ### Enum ```json theme={null} { "priority": { "type": "string", "enum": ["low", "medium", "high", "urgent"], "description": "Priority level" } } ``` ### Array ```json theme={null} { "items": { "type": "array", "items": { "type": "string" }, "description": "List of items" } } ``` ### Object ```json theme={null} { "address": { "type": "object", "properties": { "street": { "type": "string" }, "city": { "type": "string" }, "zip": { "type": "string" } }, "required": ["street", "city"] } } ``` *** ## HTTP Methods ### GET Retrieve data without side effects: ```json theme={null} { "http_method": "GET", "api_endpoint": "https://api.yourcompany.com/customers/{{customer_id}}", "query_params": { "include": "orders,profile" } } ``` ### POST Create new resources or submit data: ```json theme={null} { "http_method": "POST", "api_endpoint": "https://api.yourcompany.com/orders", "body_template": { "customer_id": "{{customer_id}}", "items": "{{items}}" } } ``` ### PUT Update existing resources: ```json theme={null} { "http_method": "PUT", "api_endpoint": "https://api.yourcompany.com/customers/{{customer_id}}", "body_template": { "phone": "{{phone_number}}", "email": "{{email}}" } } ``` *** ## Authentication ### Bearer Token ```json theme={null} { "headers": { "Authorization": "Bearer {{API_KEY}}" } } ``` ### API Key Header ```json theme={null} { "headers": { "X-API-Key": "{{API_KEY}}" } } ``` ### Basic Auth ```json theme={null} { "headers": { "Authorization": "Basic {{BASE64_CREDENTIALS}}" } } ``` Never hardcode API keys. Use environment variables: `{{API_KEY}}`. *** ## Next Steps View ready-to-use function examples Learn function calling best practices # Best Practices Source: https://docs.dialgen.ai/guides/custom-functions/best-practices Tips for reliable, secure, and effective custom function calling. ## Writing Effective Descriptions The description is the most critical part of your function definition. ### Be Specific **❌ Bad:** ```json theme={null} { "description": "Gets data" } ``` **✅ Good:** ```json theme={null} { "description": "Retrieves the customer's order status including tracking number, current location, and estimated delivery date. Call this when the customer asks about their order, delivery, shipping, or tracking." } ``` ### Include Trigger Examples ```json theme={null} { "description": "Books a hotel room. Call this when the customer wants to make a reservation. Example triggers: 'I'd like to book a room', 'Can you reserve a hotel for me', 'I need accommodation for next week'" } ``` ### Specify When NOT to Call ```json theme={null} { "description": "Cancels an order. Call this ONLY when the customer explicitly requests to cancel their order. Do NOT call this for returns, modifications, or general inquiries." } ``` *** ## Parameter Design ### Use Enums for Constrained Values **❌ Bad:** ```json theme={null} { "priority": { "type": "string", "description": "Priority level" } } ``` **✅ Good:** ```json theme={null} { "priority": { "type": "string", "enum": ["low", "medium", "high", "urgent"], "description": "Priority level for the request" } } ``` ### Provide Clear Descriptions ```json theme={null} { "appointment_date": { "type": "string", "description": "Appointment date in YYYY-MM-DD format. Must be a future date. Example: 2025-12-25" } } ``` ### Set Validation Rules ```json theme={null} { "quantity": { "type": "number", "minimum": 1, "maximum": 100, "description": "Quantity to order (between 1 and 100)" } } ``` *** ## Security ### Never Hardcode Secrets **❌ Bad:** ```json theme={null} { "headers": { "Authorization": "Bearer sk_live_abc123xyz789..." } } ``` **✅ Good:** ```json theme={null} { "headers": { "Authorization": "Bearer {{API_KEY}}" } } ``` ### Use Environment Variables Store sensitive data in environment variables: * `{{API_KEY}}` * `{{DATABASE_URL}}` * `{{WEBHOOK_SECRET}}` ### Validate Inputs Add validation in your API: ```javascript theme={null} app.post('/api/orders', (req, res) => { const { order_id, quantity } = req.body; // Validate inputs if (!order_id || typeof order_id !== 'string') { return res.status(400).json({ error: 'Invalid order_id' }); } if (!quantity || quantity < 1 || quantity > 100) { return res.status(400).json({ error: 'Invalid quantity' }); } // Process request }); ``` ### Implement Rate Limiting ```javascript theme={null} const rateLimit = require('express-rate-limit'); const limiter = rateLimit({ windowMs: 60 * 1000, // 1 minute max: 100 // Max 100 requests per minute }); app.use('/api/', limiter); ``` *** ## Error Handling ### Return Clear Error Messages ```json theme={null} { "error": "Order not found", "code": "ORDER_NOT_FOUND", "message": "The order ID provided does not exist or you don't have access to it" } ``` ### Handle Timeouts Set reasonable timeouts: ```json theme={null} { "timeout": 10000 } ``` ### Provide Fallbacks ```text theme={null} FUNCTION ERROR HANDLING: - If the API call fails, say: "I'm having trouble accessing that information right now. Let me transfer you to a team member who can help." - If the order is not found, say: "I couldn't find that order number. Can you please verify the order number?" ``` *** ## Performance ### Keep Responses Fast * Optimize API response time (\< 2 seconds) * Use caching where appropriate * Return only necessary data ### Minimize Function Calls * Batch operations when possible * Cache frequently accessed data * Avoid redundant calls ### Use Async Processing For long-running operations: ```json theme={null} { "api_endpoint": "https://api.yourcompany.com/jobs", "http_method": "POST", "body_template": { "operation": "generate_report", "callback_url": "https://dialgen.ai/callbacks/{{call_sid}}" } } ``` *** ## Testing ### Test with Sample Data ```json theme={null} { "test_parameters": { "order_id": "TEST_ORDER_123", "customer_id": "TEST_CUSTOMER_456" } } ``` ### Use Staging Endpoints ```json theme={null} { "api_endpoint": "https://api-staging.yourcompany.com/orders" } ``` ### Log Everything ```javascript theme={null} app.post('/api/orders', (req, res) => { console.log('Function called:', { timestamp: new Date().toISOString(), body: req.body, headers: req.headers }); // Process request }); ``` *** ## Documentation ### Document Your Functions Create internal documentation: ```markdown theme={null} ## check_order_status **Purpose**: Retrieve order status and tracking **Triggers**: - "Where is my order?" - "What's the status of order #123?" - "Track my shipment" **Parameters**: - order_id (required): Order number **Returns**: - status: Order status - tracking_number: Tracking number - estimated_delivery: Delivery date ``` ### Version Your APIs Use versioned endpoints: ```json theme={null} { "api_endpoint": "https://api.yourcompany.com/v1/orders" } ``` *** ## Next Steps Learn how to test and debug functions Complete API integration guide # Function Examples Source: https://docs.dialgen.ai/guides/custom-functions/examples Ready-to-use function examples for common use cases. ## CRM Integration ### Update Lead Status ```json theme={null} { "name": "update_lead_status", "description": "Updates the lead status in the CRM. Call this when the customer expresses their interest level. Use 'hot' for very interested, 'warm' for interested, 'cold' for not interested.", "parameters": { "type": "object", "properties": { "lead_status": { "type": "string", "enum": ["hot", "warm", "cold"], "description": "The lead's interest level" }, "notes": { "type": "string", "description": "Notes about the conversation" } }, "required": ["lead_status"] }, "api_endpoint": "https://crm.yourcompany.com/api/v1/leads/{{contact_id}}", "http_method": "PUT", "headers": { "Authorization": "Bearer {{CRM_API_KEY}}" }, "body_template": { "status": "{{lead_status}}", "notes": "{{notes}}", "updated_by": "ai_agent", "call_id": "{{call_sid}}" } } ``` ### Add CRM Note ```json theme={null} { "name": "add_crm_note", "description": "Adds a note to the customer's CRM record. Use this to log important information mentioned during the call.", "parameters": { "type": "object", "properties": { "note_text": { "type": "string", "description": "The note content to add" }, "note_type": { "type": "string", "enum": ["general", "follow_up", "complaint", "feedback"], "description": "Type of note" } }, "required": ["note_text"] }, "api_endpoint": "https://crm.yourcompany.com/api/v1/contacts/{{contact_id}}/notes", "http_method": "POST", "headers": { "Authorization": "Bearer {{CRM_API_KEY}}" }, "body_template": { "content": "{{note_text}}", "type": "{{note_type}}", "created_by": "ai_agent" } } ``` *** ## Order Management ### Check Order Status ```json theme={null} { "name": "check_order_status", "description": "Retrieves the customer's order status and tracking information. Call this when the customer asks about their order, delivery, shipping, or tracking.", "parameters": { "type": "object", "properties": { "order_id": { "type": "string", "description": "The order number" } }, "required": ["order_id"] }, "api_endpoint": "https://api.yourcompany.com/orders/{{order_id}}", "http_method": "GET", "headers": { "Authorization": "Bearer {{API_KEY}}" } } ``` ### Process Return ```json theme={null} { "name": "process_return", "description": "Initiates a return request for an order. Call this when the customer wants to return a product.", "parameters": { "type": "object", "properties": { "order_id": { "type": "string", "description": "The order number to return" }, "reason": { "type": "string", "enum": ["defective", "wrong_item", "not_needed", "other"], "description": "Reason for return" }, "items": { "type": "array", "items": { "type": "string" }, "description": "List of item IDs to return" } }, "required": ["order_id", "reason"] }, "api_endpoint": "https://api.yourcompany.com/returns", "http_method": "POST", "headers": { "Authorization": "Bearer {{API_KEY}}" }, "body_template": { "order_id": "{{order_id}}", "reason": "{{reason}}", "items": "{{items}}", "customer_id": "{{contact_id}}" } } ``` *** ## Appointment Booking ### Check Availability ```json theme={null} { "name": "check_availability", "description": "Checks available appointment slots for a specific date. Call this when the customer wants to schedule an appointment.", "parameters": { "type": "object", "properties": { "date": { "type": "string", "description": "Date in YYYY-MM-DD format" }, "service_type": { "type": "string", "enum": ["consultation", "follow-up", "procedure"], "description": "Type of appointment" } }, "required": ["date"] }, "api_endpoint": "https://api.yourcompany.com/appointments/availability", "http_method": "GET", "query_params": { "date": "{{date}}", "service": "{{service_type}}" }, "headers": { "Authorization": "Bearer {{API_KEY}}" } } ``` ### Book Appointment ```json theme={null} { "name": "book_appointment", "description": "Books an appointment for the customer. Call this after confirming the date, time, and service type with the customer.", "parameters": { "type": "object", "properties": { "date": { "type": "string", "description": "Date in YYYY-MM-DD format" }, "time": { "type": "string", "description": "Time in HH:MM format (24-hour)" }, "service_type": { "type": "string", "description": "Type of appointment" } }, "required": ["date", "time", "service_type"] }, "api_endpoint": "https://api.yourcompany.com/appointments", "http_method": "POST", "headers": { "Authorization": "Bearer {{API_KEY}}" }, "body_template": { "customer_name": "{{contact_name}}", "phone": "{{from_number}}", "date": "{{date}}", "time": "{{time}}", "service": "{{service_type}}" } } ``` *** ## Communication ### Send SMS ```json theme={null} { "name": "send_sms", "description": "Sends an SMS message to the customer. Use this to send confirmation codes, appointment reminders, or important information.", "parameters": { "type": "object", "properties": { "message": { "type": "string", "description": "The message to send" } }, "required": ["message"] }, "api_endpoint": "https://api.twilio.com/2010-04-01/Accounts/{{TWILIO_ACCOUNT_SID}}/Messages.json", "http_method": "POST", "headers": { "Authorization": "Basic {{TWILIO_AUTH_TOKEN}}" }, "body_template": { "To": "{{from_number}}", "From": "{{to_number}}", "Body": "{{message}}" } } ``` ### Send Email ```json theme={null} { "name": "send_email", "description": "Sends an email to the customer. Use this to send detailed information, documents, or follow-up materials.", "parameters": { "type": "object", "properties": { "subject": { "type": "string", "description": "Email subject line" }, "body": { "type": "string", "description": "Email body content" } }, "required": ["subject", "body"] }, "api_endpoint": "https://api.yourcompany.com/emails/send", "http_method": "POST", "headers": { "Authorization": "Bearer {{API_KEY}}" }, "body_template": { "to": "{{contact_email}}", "subject": "{{subject}}", "body": "{{body}}", "from": "noreply@yourcompany.com" } } ``` *** ## Data Retrieval ### Get Customer Profile ```json theme={null} { "name": "get_customer_profile", "description": "Retrieves the customer's profile information including account details and preferences. Call this when you need customer information.", "parameters": { "type": "object", "properties": { "customer_id": { "type": "string", "description": "The customer ID" } }, "required": ["customer_id"] }, "api_endpoint": "https://api.yourcompany.com/customers/{{customer_id}}", "http_method": "GET", "headers": { "Authorization": "Bearer {{API_KEY}}" } } ``` ### Search Products ```json theme={null} { "name": "search_products", "description": "Searches for products in the catalog. Call this when the customer asks about products, pricing, or availability.", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "Search query" }, "category": { "type": "string", "description": "Product category to filter by" }, "max_price": { "type": "number", "description": "Maximum price filter" } }, "required": ["query"] }, "api_endpoint": "https://api.yourcompany.com/products/search", "http_method": "GET", "query_params": { "q": "{{query}}", "category": "{{category}}", "max_price": "{{max_price}}" }, "headers": { "Authorization": "Bearer {{API_KEY}}" } } ``` *** ## Next Steps Learn function calling best practices How to test and debug functions # Custom Function Calling Source: https://docs.dialgen.ai/guides/custom-functions/overview Integrate external APIs and workflows into your AI agents with function calling. ## What is Function Calling? Function calling enables your AI agents to execute real-time actions during conversations by calling external APIs and triggering workflows. *** ## Capabilities Connect to external APIs and services Ready-to-use function examples for common use cases Tips for reliable and secure function calling How to test and debug custom functions *** ## How It Works The AI understands what the function does from its description Based on conversation, AI decides when to call the function AI collects required parameters from the conversation Dialgen makes the HTTP request to your endpoint API response feeds back to AI for natural continuation *** ## Quick Example ```json theme={null} { "name": "check_order_status", "description": "Checks the customer's order status. Call this when the customer asks about their order, delivery, or tracking.", "parameters": { "type": "object", "properties": { "order_id": { "type": "string", "description": "The order number" } }, "required": ["order_id"] }, "api_endpoint": "https://api.yourcompany.com/orders/status", "http_method": "POST" } ``` The description is critical. The AI relies on it to know when to trigger the function. *** ## Use Cases ### CRM Integration Update customer records, add notes, change lead status. ### Appointment Booking Check availability and book appointments in real-time. ### Order Management Check order status, process returns, track shipments. ### Payment Processing Process payments, check balances, send invoices. ### Data Retrieval Fetch customer data, account information, product details. *** ## Next Steps Learn how to integrate external APIs View ready-to-use function examples # Testing Functions Source: https://docs.dialgen.ai/guides/custom-functions/testing Test and debug custom functions before deploying to production. ## Testing Strategy Follow this approach to ensure your functions work reliably: Test your API endpoint independently Test function definition with sample parameters Test with live agent conversations Monitor function calls in production *** ## Unit Testing Your API Test your API endpoint before integrating: ### Using curl ```bash theme={null} curl -X POST https://api.yourcompany.com/orders/status \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "order_id": "TEST_123" }' ``` ### Using Postman 1. Create a new request 2. Set method and URL 3. Add headers 4. Add request body 5. Send and verify response ### Expected Response Ensure your API returns: * Consistent JSON structure * Appropriate status codes * Clear error messages * Fast response time (\< 2s) *** ## Testing Function Definitions ### Validate JSON Schema Use online validators: * [JSON Schema Validator](https://www.jsonschemavalidator.net/) * [Swagger Editor](https://editor.swagger.io/) ### Test with Sample Parameters ```json theme={null} { "function": "check_order_status", "test_parameters": { "order_id": "TEST_ORDER_123" }, "expected_response": { "status": "shipped", "tracking_number": "1Z999AA10123456784" } } ``` *** ## Conversation Testing ### Create Test Scenarios **Scenario 1: Happy Path** ```text theme={null} User: "I want to check my order status" Agent: "I'd be happy to help. What's your order number?" User: "It's ORDER-123" Agent: [Calls check_order_status function] Agent: "Your order is currently in transit and will arrive on Friday" ``` **Scenario 2: Missing Information** ```text theme={null} User: "Check my order" Agent: "I'll check that for you. What's your order number?" User: "I don't have it" Agent: "No problem. Can you provide your email address?" ``` **Scenario 3: Error Handling** ```text theme={null} User: "Order number ABC-999" Agent: [Calls function, receives 404 error] Agent: "I couldn't find that order number. Could you verify it's correct?" ``` ### Test Checklist * ✓ Function triggers at the right time * ✓ Parameters are extracted correctly * ✓ API call succeeds * ✓ Response is interpreted correctly * ✓ Agent continues conversation naturally * ✓ Errors are handled gracefully *** ## Debugging ### Enable Logging Log all function calls: ```javascript theme={null} app.post('/api/orders/status', (req, res) => { console.log('Function call received:', { timestamp: new Date().toISOString(), callId: req.headers['x-call-id'], body: req.body, source: req.headers['user-agent'] }); // Process request console.log('Function response:', { status: 200, data: responseData }); res.json(responseData); }); ``` ### Common Issues #### Function Not Triggering **Symptoms:** * Agent doesn't call the function when expected **Debug Steps:** 1. Check function description is clear 2. Add more trigger examples 3. Make conditions more explicit 4. Test with direct requests #### Wrong Parameters Extracted **Symptoms:** * Function called with incorrect parameter values **Debug Steps:** 1. Improve parameter descriptions 2. Add format examples 3. Use enums to constrain values 4. Add validation in prompt #### API Call Fails **Symptoms:** * Function triggers but API returns error **Debug Steps:** 1. Test API endpoint with curl 2. Check authentication headers 3. Verify parameter format 4. Review API logs *** ## Monitoring Production ### Track Function Calls Monitor these metrics: * Function call frequency * Success rate * Average response time * Error rate by type ### Set Up Alerts Alert on: * High error rate (> 5%) * Slow response time (> 5s) * Authentication failures * Unexpected errors ### Review Logs Regularly review: * Function call logs * API error logs * Agent conversation logs * User feedback *** ## Testing Tools ### ngrok for Local Testing ```bash theme={null} # Start your local API node server.js # In another terminal, start ngrok ngrok http 3000 # Use ngrok URL in function definition https://abc123.ngrok.io/api/orders/status ``` ### Mock APIs Use mock APIs for testing: ```javascript theme={null} // mock-api.js const express = require('express'); const app = express(); app.post('/api/orders/status', (req, res) => { const { order_id } = req.body; // Return mock data res.json({ order_id: order_id, status: 'shipped', tracking_number: 'MOCK123', estimated_delivery: '2025-11-20' }); }); app.listen(3000); ``` *** ## Best Practices ### Start Simple Begin with simple functions: 1. Single parameter 2. Simple GET request 3. Clear success/failure states ### Iterate Based on Data 1. Deploy with logging 2. Monitor for issues 3. Adjust based on patterns 4. Refine descriptions and parameters ### Document Everything * Function purpose and triggers * Parameter formats and examples * Expected responses * Error scenarios * Testing procedures *** ## Next Steps View more function examples Complete API integration guide # Custom Metrics & Post-Call Processing Source: https://docs.dialgen.ai/guides/custom-metrics-processing Extract custom insights from calls using AI-powered metric analysis and post-call webhooks. ## What are Custom Metrics? Custom metrics allow you to define AI-powered analysis rules that extract specific insights from your calls automatically. Combined with post-call webhooks, you can send this data directly to your systems for further processing. *** ## Key Features AI analyzes call transcripts to extract custom metrics Text, Numbers, Yes/No, and List data types Send metrics to your external systems automatically Standard metrics included by default *** ## How It Works Define custom metrics with AI analysis prompts in agent settings Dialgen records and transcribes the call AI extracts metrics based on your custom prompts Complete call data and all metrics sent to your webhook URL Your system receives and processes the metrics *** ## Setting Up Custom Metrics Custom metrics are configured exclusively through the **Dialgen Dashboard**. There is no API endpoint for creating or managing custom metrics. All configuration must be done via the web interface. ### Dashboard Configuration 1. Navigate to your agent settings 2. Go to the **Metrics** tab 3. Scroll to **Custom Metrics** section 4. Click **Add Custom Metric** 5. Configure: * **Metric Name**: What to call this metric * **Data Type**: Text, Number, Yes/No, or List * **AI Analysis Prompt**: Instructions for AI extraction * **Required**: Whether this metric must always have a value * **Description**: Optional notes about this metric 6. Click **Create Metric** or **Update Metric** to save Once configured, your custom metrics will be automatically applied to all calls for that agent. ### Configuration Example ```json theme={null} { "name": "Customer Satisfaction Score", "dataType": "number", "prompt": "Rate the customer's satisfaction level on a scale of 1-10 based on their tone, responses, and any explicit feedback given during the call.", "isRequired": true, "description": "Numerical satisfaction score for tracking customer happiness" } ``` *** ## Data Types Choose the appropriate data type for your metric: ### Text (String) Store textual responses or extracted information. **Example:** ```json theme={null} { "name": "Product Interest", "dataType": "string", "prompt": "What products or services did the customer express interest in?" } ``` **API Response:** ```json theme={null} { "product_interest": "Enterprise plan and support services" } ``` ### Number Store numerical values like scores, ratings, or counts. **Example:** ```json theme={null} { "name": "Sentiment Score", "dataType": "number", "prompt": "Rate the customer's sentiment on a scale of -10 (very negative) to +10 (very positive)", "isRequired": true } ``` **API Response:** ```json theme={null} { "sentiment_score": 7 } ``` ### Yes/No (Boolean) Store true/false values for yes/no questions. **Example:** ```json theme={null} { "name": "Callback Needed", "dataType": "boolean", "prompt": "Did the customer request a callback or follow-up call?" } ``` **API Response:** ```json theme={null} { "callback_needed": true } ``` ### List (Array) Store multiple values as a list. **Example:** ```json theme={null} { "name": "Mentioned Issues", "dataType": "array", "prompt": "List all technical issues or problems mentioned by the customer during the call" } ``` **API Response:** ```json theme={null} { "mentioned_issues": [ "Login timeout", "Mobile app crashes", "Password reset issues" ] } ``` *** ## Default Metrics Dialgen includes standard metrics for every call. These are always included unless explicitly disabled: | Metric | Type | Description | | ------------------ | ------ | ---------------------------------------------- | | `summary` | string | Overall call summary | | `intent` | string | Primary customer intent | | `sentiment` | string | Customer sentiment (positive/neutral/negative) | | `confidence` | number | AI confidence in the analysis (0-1) | | `keyPoints` | array | Key discussion points | | `actionItems` | array | Items requiring follow-up action | | `callStatus` | string | Call status (SUCCESS, UNRESOLVED, ESCALATION) | | `callbackRequired` | string | Whether callback is needed | | `promisedDate` | string | Any promised date mentioned | | `selfEvaluation` | array | Agent's self-evaluation of performance | | `followUpAction` | string | Recommended follow-up action | | `ticketRaised` | string | Support ticket number if created | ### Disable Default Metrics You can disable default metrics if you only want custom ones: 1. In the **Metrics** tab 2. Find **Default Dialgen Metrics** section 3. Toggle **Enable** switch to OFF Disabling default metrics means standard analysis data won't be generated. Only do this if you have custom metrics that cover the metrics you need. *** ## Post-Call Webhooks ### What are Post-Call Webhooks? Post-call webhooks are HTTP POST requests sent to your server immediately after a call completes. They contain: * Complete call data * All default metrics * All custom metrics with their schema * Recording URL and transcript The schema of your defined custom metrics is automatically included in every webhook payload so your system knows how to process each metric. ### Configuration 1. Go to **Metrics** tab in agent settings 2. Find **Post-Call Webhook** section 3. Enter your webhook URL: `https://api.yourdomain.com/webhook` 4. Save Once saved, all future calls will send metrics with the complete schema to this endpoint. ### Webhook Payload with Schema ```json theme={null} { "success": true, "callData": { "id": "call_789", "contactId": "contact_ABC", "agentId": "agent_XYZ", "batchId": "batch_456", "status": "COMPLETED", "startTime": "2025-11-16T10:15:30.000Z", "endTime": "2025-11-16T10:22:45.000Z", "duration": 435, "phoneNumber": "+14155552671", "contactName": "Sarah Anderson", "recordingUrl": "https://recordings.dialgen.ai/call_789.mp3", "transcription": [ { "role": "assistant", "content": "Hello! Thanks for calling TechCorp. How can I assist you today?" }, { "role": "user", "content": "Hi, I'm interested in your enterprise solution" }, { "role": "assistant", "content": "Great! Let me tell you about our enterprise features..." } ], // Default Dialgen metrics "summary": "Customer called regarding enterprise solution pricing and features. Expressed strong interest in features like multi-team collaboration and advanced analytics. Requested pricing details.", "intent": "SALES_INQUIRY", "sentiment": "positive", "confidence": 0.94, "keyPoints": [ "Interested in enterprise plan", "Wants multi-team collaboration", "Needs advanced analytics" ], "actionItems": [ "Send enterprise pricing document", "Schedule product demo", "Provide ROI calculator" ], "callStatus": "SUCCESS", "callbackRequired": "false", "promisedDate": "2025-11-20", "followUpAction": "Send pricing and schedule demo", // Custom metrics with schema "customMetrics": { "lead_score": { "value": 92, "schema": { "type": "number", "name": "Lead Score", "description": "Lead quality rating on scale 1-100", "isRequired": true } }, "use_case": { "value": "Multi-team project collaboration platform for software development teams", "schema": { "type": "string", "name": "Use Case", "description": "Primary use case mentioned by customer", "isRequired": true } }, "budget_range": { "value": [ "$5000-10000 annually" ], "schema": { "type": "array", "name": "Budget Range", "description": "Budget constraints mentioned", "isRequired": false } }, "product_features_interest": { "value": [ "Multi-team collaboration", "Advanced analytics dashboard", "API integration", "Single sign-on", "Audit logs" ], "schema": { "type": "array", "name": "Product Features Interest", "description": "Features customer expressed interest in", "isRequired": false } }, "has_budget_approved": { "value": true, "schema": { "type": "boolean", "name": "Has Budget Approved", "description": "Whether customer has budget approval", "isRequired": false } }, "competitor_mentioned": { "value": "Slack, Monday.com", "schema": { "type": "string", "name": "Competitor Mentioned", "description": "Competing solutions mentioned", "isRequired": false } } } }, // Schema definition (sent once per webhook) "metricSchema": { "lead_score": { "type": "number", "name": "Lead Score", "description": "Lead quality rating on scale 1-100", "isRequired": true }, "use_case": { "type": "string", "name": "Use Case", "description": "Primary use case mentioned by customer", "isRequired": true }, "budget_range": { "type": "array", "name": "Budget Range", "description": "Budget constraints mentioned", "isRequired": false }, "product_features_interest": { "type": "array", "name": "Product Features Interest", "description": "Features customer expressed interest in", "isRequired": false }, "has_budget_approved": { "type": "boolean", "name": "Has Budget Approved", "description": "Whether customer has budget approval", "isRequired": false }, "competitor_mentioned": { "type": "string", "name": "Competitor Mentioned", "description": "Competing solutions mentioned", "isRequired": false } } } ``` The `metricSchema` field contains the complete definition of all custom metrics, including their type, description, and whether they're required. This allows your system to properly validate and process the custom metric values. *** ## Processing Webhooks ### Node.js Example ```javascript theme={null} const express = require('express'); const app = express(); app.use(express.json()); app.post('/webhook', async (req, res) => { const { callData, metricSchema } = req.body; try { // Extract custom metrics const metrics = callData.customMetrics || {}; console.log('Call Analysis:'); console.log(`- Lead Score: ${metrics.lead_score?.value}`); console.log(`- Use Case: ${metrics.use_case?.value}`); console.log(`- Has Budget: ${metrics.has_budget_approved?.value}`); console.log(`- Features Interest: ${metrics.product_features_interest?.value?.join(", ")}`); // Use metricSchema to validate and process metrics Object.entries(metricSchema).forEach(([key, schema]) => { const metricValue = metrics[key]?.value; const isRequired = schema.isRequired; if (isRequired && !metricValue) { console.warn(`Warning: Required metric "${schema.name}" is missing`); } }); // Update your CRM with extracted metrics await crm.updateContact({ id: callData.contactId, lastCallDate: callData.startTime, leadScore: metrics.lead_score?.value, useCase: metrics.use_case?.value, budgetApproved: metrics.has_budget_approved?.value, featuresInterested: metrics.product_features_interest?.value }); // Create sales opportunity if lead score is high if (metrics.lead_score?.value >= 80) { await crm.createOpportunity({ contactId: callData.contactId, title: `Enterprise Sales: ${metrics.use_case?.value}`, value: 50000, // Estimated based on budget range stage: 'DISCOVERY' }); } // Schedule follow-up if callback requested (if you had such metric) if (metrics.has_budget_approved?.value) { await scheduling.createTask({ contactId: callData.contactId, type: 'PRODUCT_DEMO', dueDate: '2025-11-20', priority: 'HIGH' }); } res.status(200).json({ success: true }); } catch (error) { console.error('Webhook processing error:', error); res.status(200).json({ success: true }); // Still return 200 to prevent retries } }); app.listen(3000); ``` ### Python Example ```python theme={null} from flask import Flask, request, jsonify from datetime import datetime, timedelta app = Flask(__name__) @app.route('/webhook', methods=['POST']) def webhook(): data = request.json call_data = data.get('callData', {}) metrics = call_data.get('customMetrics', {}) metric_schema = data.get('metricSchema', {}) print('Call Analysis:') print(f"- Lead Score: {metrics.get('lead_score', {}).get('value')}") print(f"- Use Case: {metrics.get('use_case', {}).get('value')}") print(f"- Has Budget: {metrics.get('has_budget_approved', {}).get('value')}") features = metrics.get('product_features_interest', {}).get('value', []) print(f"- Features Interest: {', '.join(features)}") # Validate required metrics using schema for key, schema in metric_schema.items(): metric_value = metrics.get(key, {}).get('value') is_required = schema.get('isRequired', False) if is_required and not metric_value: print(f"Warning: Required metric '{schema.get('name')}' is missing") # Update CRM crm.update_contact({ 'id': call_data.get('contactId'), 'last_call': call_data.get('startTime'), 'lead_score': metrics.get('lead_score', {}).get('value'), 'use_case': metrics.get('use_case', {}).get('value'), 'budget_approved': metrics.get('has_budget_approved', {}).get('value'), 'features_interested': metrics.get('product_features_interest', {}).get('value') }) # Create opportunity if high lead score lead_score = metrics.get('lead_score', {}).get('value', 0) if lead_score >= 80: crm.create_opportunity({ 'contact_id': call_data.get('contactId'), 'title': f"Enterprise Sales: {metrics.get('use_case', {}).get('value')}", 'value': 50000, 'stage': 'DISCOVERY' }) # Schedule demo if budget is approved if metrics.get('has_budget_approved', {}).get('value'): scheduling.create_task({ 'contact_id': call_data.get('contactId'), 'type': 'PRODUCT_DEMO', 'due_date': (datetime.now() + timedelta(days=4)).isoformat(), 'priority': 'HIGH' }) return jsonify({'success': True}), 200 if __name__ == '__main__': app.run(port=3000) ``` *** ## Best Practices ### Writing Effective Prompts **❌ Vague:** ``` Extract the customer's feedback ``` **✅ Specific:** ``` Did the customer express satisfaction with the service? If yes, rate their satisfaction level 1-10. If no, explain why they were dissatisfied. ``` ### Choose Right Data Types | Metric Type | Best Data Type | | ------------------------ | -------------- | | Scores or ratings | Number | | Yes/No decisions | Boolean | | Multiple values | Array | | Descriptions or feedback | String | ### Required Fields Mark metrics as "Required" only when: * The metric must always have a value * Missing values would cause problems in your system * You want to validate quality ### Testing Metrics 1. **Create test agents** with your metrics 2. **Run test calls** with various scenarios 3. **Review webhook payloads** to verify accuracy 4. **Adjust prompts** based on results 5. **Deploy** when confident ### Security * ✓ Validate webhook signatures if possible * ✓ Use HTTPS URLs only * ✓ Implement rate limiting * ✓ Log all webhook activity * ✓ Handle errors gracefully *** ## Common Use Cases ### Lead Scoring ```json theme={null} { "name": "Lead Score", "dataType": "number", "prompt": "Rate the lead quality on a scale of 1-100 based on their interest level, budget clarity, and buying timeline.", "isRequired": true } ``` ### Sentiment Tracking ```json theme={null} { "name": "Customer Emotion", "dataType": "string", "prompt": "Describe the customer's emotional state during the call (happy, frustrated, neutral, angry, confused)" } ``` ### Issue Documentation ```json theme={null} { "name": "Technical Issues", "dataType": "array", "prompt": "List each technical issue or bug the customer reported" } ``` ### Follow-up Actions ```json theme={null} { "name": "Required Follow-ups", "dataType": "array", "prompt": "What specific actions must be taken before the next customer contact?" } ``` *** ## Troubleshooting ### Webhook Not Received **Check:** * URL is correct and publicly accessible * Server is responding with 2xx status code * Firewall isn't blocking incoming requests * Check Dialgen logs for errors ### Metrics Empty or Incorrect **Solutions:** * Review and clarify your AI prompt * Provide examples in the prompt * Use simpler, more direct language * Test with different call scenarios ### High CPU Usage **Optimization:** * Reduce number of custom metrics * Simplify AI prompts * Disable default metrics if not needed * Increase webhook processing interval *** ## Retrieving Metrics via API In addition to webhooks, you can retrieve custom metrics by calling the `get-call-metric` endpoint. The endpoint will return the complete schema definition for all custom metrics configured for that agent. ### Get Call Metrics Endpoint ```bash theme={null} curl --location 'https://sa.dialgen.ai/api/v1/call/get-metric?callId=call_789&userId=user_456&agentId=agent_XYZ&contactId=contact_ABC' \ -H 'Authorization: Bearer YOUR_API_KEY' ``` ### Response with Custom Metric Schema ```json theme={null} { "success": true, "callData": { "id": "call_789", "status": "COMPLETED", "duration": 435, "recordingUrl": "https://recordings.dialgen.ai/call_789.mp3", // Default metrics... "summary": "Customer inquiry about enterprise solution...", "intent": "SALES_INQUIRY", "sentiment": "positive", // Custom metrics with schema "customMetrics": { "lead_score": { "value": 92, "schema": { "type": "number", "name": "Lead Score", "description": "Lead quality rating on scale 1-100", "isRequired": true } }, "use_case": { "value": "Multi-team project collaboration", "schema": { "type": "string", "name": "Use Case", "description": "Primary use case mentioned by customer", "isRequired": true } }, "product_features_interest": { "value": ["Multi-team collaboration", "Advanced analytics", "API integration"], "schema": { "type": "array", "name": "Product Features Interest", "description": "Features customer expressed interest in", "isRequired": false } }, "has_budget_approved": { "value": true, "schema": { "type": "boolean", "name": "Has Budget Approved", "description": "Whether customer has budget approval", "isRequired": false } } } }, "metricSchema": { "lead_score": { "type": "number", "name": "Lead Score", "description": "Lead quality rating on scale 1-100", "isRequired": true }, "use_case": { "type": "string", "name": "Use Case", "description": "Primary use case mentioned by customer", "isRequired": true }, "product_features_interest": { "type": "array", "name": "Product Features Interest", "description": "Features customer expressed interest in", "isRequired": false }, "has_budget_approved": { "type": "boolean", "name": "Has Budget Approved", "description": "Whether customer has budget approval", "isRequired": false } } } ``` Both the `get-call-metric` endpoint and the `onCallComplete` webhook return the complete metric schema, allowing your application to properly understand and validate each custom metric's structure. *** ## Next Steps Learn how to configure agents Complete API documentation Access call data and recordings # Genesys Cloud Integration Source: https://docs.dialgen.ai/guides/genesys-integration Connect Dialgen with Genesys Cloud's Audio Connector for bi-directional audio streaming ## Genesys Cloud Integration Dialgen supports integration with **Genesys Cloud's Audio Connector** for seamless bi-directional audio streaming. This integration enables you to connect Dialgen's AI agents with Genesys Cloud's contact center infrastructure. ### Supported Features Real-time audio exchange between Genesys Cloud and Dialgen AI agents Automatic call routing to appropriate agents via AgentID Support for ANI, DNIS, conversation ID, and custom metadata Graceful error handling and fallback mechanisms ### Integration Status The Genesys Audio Connector integration is currently in **active development and deployment phase**. ### How It Works When Genesys Cloud initiates an audio stream through the Audio Connector: 1. **Authentication** - Your Genesys environment connects using provided credentials 2. **Agent Routing** - Calls are routed to the specified Dialgen agent 3. **Audio Processing** - The AI agent processes the incoming audio in real-time 4. **Response Streaming** - Processed audio is streamed back to Genesys Cloud ### Key Components | Component | Description | | ------------------- | ---------------------------------------------------------- | | **ConnectorID** | Unique identifier assigned by Genesys for your integration | | **AgentID** | Your Dialgen agent identifier for call routing | | **WSS Endpoint** | WebSocket endpoint for real-time audio streaming | | **API Credentials** | Authentication credentials for secure connection | ### Getting Started To set up Genesys Audio Connector integration, you'll need: * A Genesys Cloud account with Audio Connector enabled * Configured Dialgen agents ready for integration * Technical team access for credential exchange and setup ### For Detailed Information For comprehensive integration details, including: * Architecture documentation * Configuration guidelines * Implementation steps * Testing procedures * Troubleshooting guides **Please contact the Dialgen team:** * 📧 Email: \[[team@dialgen.ai](mailto:team@dialgen.ai)] * 💬 Slack: #dialgen-support * 📞 Support: \[support-contact] ### Frequently Asked Questions PCM/G.711 @ 8000 Hz (mono) - Standard Genesys Audio Connector format with configurable options for advanced use cases. Configurable per agent, with a default of 600 seconds (10 minutes) per call. Calls are authenticated using API credentials (Key + Secret) provided during setup, with additional ConnectorID validation. Fallback mechanisms are in place to handle agent unavailability and ensure graceful error handling back to Genesys. Yes, you can configure multiple agents for different use cases and route calls accordingly via AgentID. ### Next Steps Ready to integrate? Contact the Dialgen team to: 1. Verify your Genesys Cloud setup 2. Exchange authentication credentials securely 3. Configure your agents for integration 4. Begin testing and deployment *** **Last Updated:** February 18, 2026\ **Status:** Documentation\ **Next Phase:** Production Deployment # Dynamic Language Switching Source: https://docs.dialgen.ai/guides/multilingual/dynamic-switching Enable automatic language detection and switching during conversations. ## What is Dynamic Language Switching? Dynamic language switching allows your agent to detect and adapt to the language spoken by the caller, switching languages mid-conversation when needed. *** ## How It Works The caller speaks in their preferred language The speech-to-text system detects the language The agent responds in the detected language The agent continues in that language for the rest of the call *** ## Configuration Add language switching instructions to your agent prompt: ```text theme={null} You are a multilingual customer support agent for Acme Corp. LANGUAGE RULES: - Start the conversation in English - If the customer responds in Spanish, immediately switch to Spanish - If the customer responds in French, immediately switch to French - Once you switch languages, continue in that language for the entire call - Always match the customer's language preference IMPORTANT: Generate all responses in the same language as the customer's last message. ``` *** ## Supported Language Pairs ### English + Spanish ```text theme={null} LANGUAGE RULES: - Start in English - If customer speaks Spanish, switch to Spanish immediately - Remain in Spanish for the rest of the call - Use formal "usted" form unless customer uses informal "tú" ``` ### English + French ```text theme={null} RÈGLES LINGUISTIQUES: - Commencer en anglais - Si le client parle français, passer immédiatement au français - Rester en français pour le reste de l'appel - Utiliser le vouvoiement sauf si le client tutoie ``` ### English + Hindi ```text theme={null} भाषा नियम: - अंग्रेजी में शुरू करें - यदि ग्राहक हिंदी में बोलता है, तुरंत हिंदी में स्विच करें - पूरी कॉल के लिए हिंदी में रहें - हमेशा सम्मानजनक भाषा का उपयोग करें ``` ### English + Arabic ```text theme={null} قواعد اللغة: - ابدأ باللغة الإنجليزية - إذا تحدث العميل باللغة العربية، انتقل إلى العربية فوراً - استمر في التحدث بالعربية لبقية المكالمة - استخدم دائماً لغة احترافية وودية ``` ### English + Arabic + Hindi (Trilingual) For markets serving English, Arabic, and Hindi speakers (Middle East + India): ```text theme={null} LANGUAGE RULES: - Start the conversation in English - If customer speaks Arabic, immediately switch to Arabic - If customer speaks Hindi, immediately switch to Hindi - Once you identify their language preference, continue in that language for the entire call - Never mix languages in a single response ARABIC RESPONSES: When speaking Arabic (Saudi dialect): - Use professional and respectful tone - Include proper Arabic punctuation and diacriticals - Example greeting: "السلام عليكم، كيف يمكنني مساعدتك؟" HINDI RESPONSES: When speaking Hindi: - Use native Devanagari script only (never romanized) - Include proper diacritical marks - Example greeting: "नमस्ते! मैं आपकी मदद कैसे कर सकता हूं?" ENGLISH RESPONSES: When speaking English: - Use clear, professional language - Be friendly and helpful - Example greeting: "Hello! How can I help you today?" CRITICAL: Detect language from customer's first response and stick with it for the entire call. ``` Limit dynamic switching to 2-3 languages maximum. Supporting too many languages may reduce accuracy. For trilingual setup (English + Arabic + Hindi), ensure you have thoroughly tested all combinations. *** ## Example: Bilingual Agent Here's a complete example for an English-Spanish agent: ```text theme={null} You are a bilingual customer support agent for Acme Corp. You speak both English and Spanish fluently. LANGUAGE DETECTION: - Listen carefully to the customer's first response - If they speak in Spanish, immediately switch to Spanish - If they speak in English, continue in English - Once you identify their language, use it for the entire conversation SPANISH RESPONSES: When speaking Spanish: - Use formal "usted" form - Include proper accents and punctuation (¿ ¡) - Be warm and professional - Example greeting: "¡Hola! ¿En qué puedo ayudarle hoy?" ENGLISH RESPONSES: When speaking English: - Use clear, professional language - Be friendly and helpful - Example greeting: "Hello! How can I help you today?" IMPORTANT: Never mix languages in a single response. Choose one language and stick with it. ``` *** ## Testing Language Switching ### Test Scenarios 1. **English caller**: Start in English, remain in English 2. **Spanish caller**: Start in English, switch to Spanish after first response 3. **Mixed caller**: Handle code-switching gracefully ### Validation Checklist * ✓ Agent detects language correctly * ✓ Switch happens immediately * ✓ No language mixing in responses * ✓ Proper grammar in both languages * ✓ Cultural context is appropriate *** ## Best Practices ### Clear Instructions Make language rules explicit in your prompt: ```text theme={null} CRITICAL: If the customer speaks Spanish at any point, immediately switch to Spanish and never switch back to English. ``` ### Provide Examples Include example conversations in both languages: ```text theme={null} EXAMPLE ENGLISH CONVERSATION: Agent: "Hello! How can I help you today?" Customer: "I need help with my order." Agent: "I'd be happy to help with that. Can you provide your order number?" EXAMPLE SPANISH CONVERSATION: Agent: "¡Hola! ¿En qué puedo ayudarle hoy?" Customer: "Necesito ayuda con mi pedido." Agent: "Con gusto le ayudaré. ¿Puede proporcionarme su número de pedido?" ``` ### Handle Edge Cases ```text theme={null} EDGE CASES: - If customer uses both languages, use the language of their most recent message - If customer asks to switch languages, accommodate immediately - If language is unclear, politely ask: "Would you prefer English or Spanish?" ``` *** ## Limitations ### Language Pair Limit * Support 2-3 languages maximum per agent * More languages reduce accuracy * Create separate agents for different language pairs ### Detection Accuracy * First few words may be misdetected * Accents can affect detection * Background noise impacts accuracy ### Context Preservation * Context is maintained across language switches * Metadata variables work in all languages * Call history is preserved *** ## Next Steps View all available languages More prompt writing tips # Supported Languages Source: https://docs.dialgen.ai/guides/multilingual/languages Complete list of languages supported by Dialgen AI agents. ## Available Languages Dialgen supports the following languages for voice AI agents: | Language | Language Code | Region | | ------------------------ | ------------- | -------------- | | English (United States) | en-US | United States | | English (United Kingdom) | en-GB | United Kingdom | | English (Australia) | en-AU | Australia | | English (India) | en-IN | India | | Spanish (Spain) | es-ES | Spain | | Spanish (Mexico) | es-MX | Mexico | | Spanish (Argentina) | es-AR | Argentina | | French (France) | fr-FR | France | | French (Canada) | fr-CA | Canada | | German | de-DE | Germany | | Italian | it-IT | Italy | | Portuguese (Brazil) | pt-BR | Brazil | | Portuguese (Portugal) | pt-PT | Portugal | | Arabic (Saudi Arabia) | ar-SA | Saudi Arabia | | Hindi | hi-IN | India | | Tamil | ta-IN | India | | Telugu | te-IN | India | | Bengali | bn-IN | India | | Kannada | kn-IN | India | | Malayalam | ml-IN | India | | Marathi | mr-IN | India | | Gujarati | gu-IN | India | | Punjabi | pa-IN | India | | Odia | or-IN | India | | Japanese | ja-JP | Japan | | Korean | ko-KR | South Korea | | Chinese (Mandarin) | zh-CN | China | | Dutch | nl-NL | Netherlands | | Polish | pl-PL | Poland | | Russian | ru-RU | Russia | | Turkish | tr-TR | Turkey | Additional languages can be added upon request. Contact support if you need a specific language. *** ## Language Configuration ### In Dashboard 1. Navigate to your agent settings 2. Go to **Voice** tab 3. Select **Agent Language** from dropdown 4. Choose your target language 5. Save changes ### Via API ```json theme={null} { "basicDetails": { "agentLanguage": "es-ES" } } ``` *** ## Voice Availability Different languages have different voice options: | Language | Available Voices | Premium Voices | | --------- | ---------------- | -------------- | | English | 20+ | ✓ | | Spanish | 15+ | ✓ | | French | 10+ | ✓ | | German | 8+ | ✓ | | Arabic | 8+ | ✓ | | Hindi | 8+ | ✓ | | Tamil | 6+ | ✓ | | Telugu | 6+ | ✓ | | Kannada | 6+ | ✓ | | Bengali | 6+ | - | | Malayalam | 6+ | - | | Marathi | 6+ | ✓ | | Gujarati | 6+ | - | | Punjabi | 6+ | - | | Odia | 4+ | - | | Japanese | 8+ | ✓ | | Other | 3-5 | - | Premium voices offer more natural intonation and better pronunciation. Available for popular languages. *** ## Regional Variants Some languages have regional variants with different accents and vocabulary: ### Spanish * **es-ES**: European Spanish (Spain) * **es-MX**: Mexican Spanish * **es-AR**: Argentine Spanish ### English * **en-US**: American English * **en-GB**: British English * **en-AU**: Australian English * **en-IN**: Indian English ### French * **fr-FR**: European French * **fr-CA**: Canadian French ### Arabic * **ar-SA**: Saudi Arabic (Modern Standard Arabic with Saudi dialect) ### Indian Languages Dialgen supports multiple Indian languages, each optimized for native speakers: * **hi-IN**: Hindi (Devanagari script) * **ta-IN**: Tamil (Tamil script) * **te-IN**: Telugu (Telugu script) * **bn-IN**: Bengali (Bengali script) * **kn-IN**: Kannada (Kannada script) * **ml-IN**: Malayalam (Malayalam script) * **mr-IN**: Marathi (Devanagari script) * **gu-IN**: Gujarati (Gujarati script) * **pa-IN**: Punjabi (Gurmukhi script) * **or-IN**: Odia (Odia script) Choose the variant that matches your target audience for better engagement. For Indian languages, always write prompts in the native script, not romanized versions. *** ## Testing Languages Use the voice preview feature to test: 1. Select a language 2. Choose a voice 3. Enter sample text 4. Play preview 5. Adjust settings as needed *** ## Next Steps Learn how to write prompts in different languages Configure voice and language settings # Multilingual Support Source: https://docs.dialgen.ai/guides/multilingual/overview Deploy Dialgen AI agents in multiple languages for global reach. ## Multilingual Capabilities Dialgen AI supports multiple languages, enabling you to deploy voice agents globally. Language support is integrated across speech-to-text, LLM processing, and voice synthesis. *** ## Features View all supported languages and language codes Best practices for writing prompts in non-English languages Configure voice, accent, and language-specific settings Enable dynamic language detection and switching *** ## Quick Start Configure your agent's language in the dashboard or via API: ```json theme={null} { "basicDetails": { "agentLanguage": "es-ES", "voiceGender": "female", "voiceSpeed": 1.0 } } ``` *** ## Use Cases ### Global Customer Support Deploy agents in multiple languages for international customers. ### Regional Campaigns Target specific regions with native language agents. ### Multilingual Markets Serve diverse customer bases with language-specific agents. *** ## Next Steps See all available languages Learn how to write effective multilingual prompts # Voice Settings Source: https://docs.dialgen.ai/guides/multilingual/voice-settings Configure voice, accent, speed, and language-specific settings for your agents. ## Voice Configuration Each language has specific voice options and settings: *** ## Selecting Voices ### By Language 1. Select your target language first 2. Available voices filter automatically 3. Preview voices before selecting 4. Choose based on gender and tone ### Voice Quality Tiers | Tier | Quality | Languages | Cost | | -------- | --------- | --------- | -------- | | Standard | Good | All | Standard | | Premium | Excellent | Major | +20% | | Neural | Best | Select | +50% | Premium and neural voices provide more natural intonation and better pronunciation for professional use cases. *** ## Voice Speed Adjust speaking speed for different languages: ```json theme={null} { "voiceSpeed": 1.0 } ``` * **Range**: 0.5 - 2.0 * **Default**: 1.0 * **Recommended**: 0.8 - 1.2 for most use cases ### Language-Specific Recommendations | Language | Recommended Speed | Notes | | -------- | ----------------- | ------------------------ | | English | 1.0 | Standard pace | | Spanish | 0.9 | Slightly slower | | French | 0.95 | Clear pronunciation | | German | 0.9 | Complex compound words | | Hindi | 0.85 | Ensure clarity | | Japanese | 1.0 | Standard pace works well | *** ## Voice Gender Select voice gender based on your brand and use case: ```json theme={null} { "voiceGender": "female" } ``` * **Options**: `male`, `female`, `neutral` * **Availability**: Varies by language Not all languages have all gender options. Check available voices for your selected language. *** ## Testing Voices ### Preview Feature 1. Navigate to agent settings 2. Go to **Voice** tab 3. Select language and voice 4. Enter sample text 5. Click **Preview** 6. Adjust settings as needed ### Sample Text Use realistic conversation samples: **English:** ```text theme={null} Hello! Thank you for calling. How can I help you today? ``` **Spanish:** ```text theme={null} ¡Hola! Gracias por llamar. ¿En qué puedo ayudarle hoy? ``` **French:** ```text theme={null} Bonjour ! Merci d'avoir appelé. Comment puis-je vous aider aujourd'hui ? ``` *** ## Advanced Settings ### Pitch Adjust voice pitch (where supported): ```json theme={null} { "voicePitch": 0 } ``` * **Range**: -20 to +20 * **Default**: 0 * **Note**: Not available for all voices ### Stability Control voice stability vs. expressiveness: ```json theme={null} { "voiceStability": 0.5 } ``` * **Range**: 0.0 - 1.0 * **Lower**: More expressive, varied * **Higher**: More stable, consistent *** ## Language-Specific Considerations ### Tonal Languages (Chinese, Vietnamese) * Use neural voices for better tone accuracy * Test thoroughly with native speakers * Adjust speed for clarity ### Languages with Compound Words (German, Dutch) * Slightly slower speed recommended * Ensure proper word separation * Test with long compound words ### Languages with Complex Scripts (Hindi, Arabic) * Always use native script * Verify all diacritical marks * Test pronunciation carefully *** ## Best Practices ### Match Voice to Brand * **Professional**: Use formal, clear voices * **Friendly**: Use warm, expressive voices * **Technical**: Use clear, measured voices ### Test with Native Speakers * Get feedback from native speakers * Test in real-world conditions * Adjust based on feedback ### Consider Context * **Customer support**: Clear, patient voice * **Sales**: Enthusiastic, engaging voice * **Reminders**: Friendly, brief voice *** ## Next Steps Learn how to write effective multilingual prompts Enable language detection and switching # Writing Multilingual Prompts Source: https://docs.dialgen.ai/guides/multilingual/writing-prompts Best practices for writing effective prompts in non-English languages. ## Use Native Scripts For best results, always write prompts in the native script of your target language, not phonetic English. *** ## Why Native Scripts Matter ### Better Pronunciation Native scripts help the text-to-speech engine pronounce words correctly with proper intonation. ### Accurate Language Detection Helps the AI identify the intended language and maintain consistency. ### Cultural Context Better understanding of tone, formality, and cultural nuances. ### Prevents Misclassification Avoids the AI treating romanized text as English. *** ## Language-Specific Examples ### Spanish **❌ Incorrect (No Accents):** ```text theme={null} Hola! Como estas? Vamos a comenzar. ``` **✅ Correct (With Accents):** ```text theme={null} ¡Hola! ¿Cómo estás? Vamos a comenzar. ``` **Key Points:** * Use inverted punctuation (¿ ¡) * Include accent marks (á, é, í, ó, ú, ñ) * Consider formal (usted) vs. informal (tú) ### French **❌ Incorrect:** ```text theme={null} Bonjour! Comment ca va? Nous allons commencer. ``` **✅ Correct:** ```text theme={null} Bonjour ! Comment ça va ? Nous allons commencer. ``` **Key Points:** * Include all accent marks (é, è, ê, à, ç) * Use proper apostrophes for contractions * Add space before punctuation (!, ?, :, ;) ### Hindi **❌ Incorrect (Romanized):** ```text theme={null} Namaste! Aap kaise hain? Main aapki madad kar sakta hoon. ``` **✅ Correct (Devanagari):** ```text theme={null} नमस्ते! आप कैसे हैं? मैं आपकी मदद कर सकता हूं। ``` **Key Points:** * Always use Devanagari script * Never use romanized Hindi * Include proper diacritical marks ### German **❌ Incorrect:** ```text theme={null} Guten Tag! Wie kann ich Ihnen helfen? ``` **✅ Correct:** ```text theme={null} Guten Tag! Wie kann ich Ihnen helfen? ``` **Key Points:** * Include umlauts (ä, ö, ü) and ß * Capitalize all nouns * Use formal (Sie) vs. informal (du) appropriately *** ## Tips for Writing ### Use Input Tools * **Google Input Tools**: Type in native scripts easily * **Built-in keyboards**: Use language keyboards on your device * **Copy-paste**: Use Google Translate for character reference (not full translations) ### Check Punctuation Different languages have different punctuation rules: * **Spanish**: ¿Question? ¡Exclamation! * **French**: Space before : ; ! ? * **German**: Use „quotes" instead of "quotes" ### Consider Formality Choose appropriate formality level: | Language | Formal | Informal | | -------- | ------ | -------- | | Spanish | usted | tú | | French | vous | tu | | German | Sie | du | | Hindi | आप | तुम | *** ## Example Prompts ### Customer Support (Spanish) ```text theme={null} Eres un agente de atención al cliente para Acme Corp. Tu objetivo es ayudar a los clientes con sus preguntas y resolver sus problemas de manera amable y profesional. REGLAS: - Siempre usa un tono amable y profesional - Mantén las respuestas breves y claras - Si no puedes resolver el problema, ofrece transferir la llamada - Siempre confirma que el cliente está satisfecho antes de terminar INFORMACIÓN DE LA EMPRESA: - Horario: Lunes a Viernes, 9:00 AM - 6:00 PM - Soporte técnico: soporte@acmecorp.com - Teléfono: +34 912 345 678 ``` ### Sales Agent (French) ```text theme={null} Vous êtes un agent commercial pour Acme Corp. Votre objectif est de qualifier les prospects et de présenter nos produits de manière professionnelle. RÈGLES : - Utilisez toujours le vouvoiement (vous) - Soyez courtois et professionnel - Posez des questions ouvertes pour comprendre les besoins - Ne soyez jamais insistant ou agressif - Proposez une démonstration si le prospect est intéressé PRODUITS : - Plan Starter : 99€/mois - Plan Business : 299€/mois - Plan Enterprise : Sur mesure ``` ### Appointment Booking (Hindi) ```text theme={null} आप Acme Corp के लिए एक अपॉइंटमेंट बुकिंग एजेंट हैं। आपका लक्ष्य ग्राहकों के लिए अपॉइंटमेंट शेड्यूल करना है। नियम: - हमेशा विनम्र और पेशेवर रहें - ग्राहक का नाम, फोन नंबर, और पसंदीदा तारीख पूछें - उपलब्ध समय स्लॉट की पुष्टि करें - अपॉइंटमेंट की पुष्टि दें उपलब्ध समय: - सोमवार से शुक्रवार: सुबह 9:00 बजे से शाम 6:00 बजे तक - शनिवार: सुबह 10:00 बजे से दोपहर 2:00 बजे तक ``` *** ## Common Mistakes ### Don't Use Phonetic Spelling **❌ Wrong:** ```text theme={null} Kaise ho? Main theek hoon. ``` **✅ Correct:** ```text theme={null} कैसे हो? मैं ठीक हूं। ``` ### Don't Mix Languages **❌ Wrong:** ```text theme={null} You are a Spanish agent. Respond with "Hola, como estas?" ``` **✅ Correct:** ```text theme={null} Eres un agente en español. Responde con "¡Hola! ¿Cómo estás?" ``` ### Don't Forget Cultural Context Consider cultural norms for: * Greetings and farewells * Formal vs. informal address * Business hours * Holidays and observances *** ## Next Steps View all available languages Configure language-specific voice settings # Quick Access Guide Source: https://docs.dialgen.ai/guides/quick-access Quick links to important features and documentation sections in Dialgen. ## Popular Features Quickly access the most important features and documentation: Run large-scale outbound call campaigns with contact lists Deploy agents in 30+ languages including Arabic and Indian languages Extract insights with AI-powered custom metrics and webhooks Integrate external APIs and trigger workflows during calls *** ## Call Management Control how calls execute and end: Set maximum call duration to manage resources Configure silence detection and natural call endings Monitor call status and lifecycle in real-time Access call recordings and full transcripts *** ## Batch Calling Setup Get started with batch campaigns: Format your CSV files correctly Structure contact data with custom variables Set priority, rate limits, and scheduling Track batch progress and metrics Receive real-time completion notifications *** ## API Reference Access API endpoints for integration: Place individual outbound calls via API Check live call status and metrics Create and manage batch campaigns Configure and retrieve agent settings *** ## Configuration Guides Learn how to configure key features: Configure voice, speed, and language preferences Enable multi-language support in one agent Best practices for effective agent prompts Integrate external APIs and services *** ## Implementation Examples Real-world implementation guides: CRM, orders, appointments, and SMS examples How to test and debug custom functions Security, performance, and reliability tips Process post-call data and metrics *** ## Languages & Localization Support for global markets: Complete list of 30+ supported languages Hindi, Tamil, Telugu, Bengali, Kannada, and more Arabic (Saudi Arabia) dialect support Use native scripts, not romanized text *** ## Quick Tips Verify your CSV file before uploading Write effective AI analysis prompts Optimize call rates and resource usage Handle errors gracefully in integrations *** ## Getting Help Need more information? Complete API documentation Learn about dashboard capabilities # Introduction Source: https://docs.dialgen.ai/index Dialgen is an AI-powered voice platform for programmatically initiating and monitoring high-volume call campaigns with human-like AI agents. ## What is Dialgen? Dialgen is an Autonomous Conversion Engine designed to eliminate customer wait times and operational lag. Our next-gen AI voice agents provide sub-second response times (averaging 947ms) while maintaining high vocal fidelity and emotional intelligence. By combining advanced large language models with real-time voice synthesis, Dialgen enables businesses to scale their outreach and inbound handling without sacrificing the quality of human conversation. ### Key Features Create, edit, and manage AI agents with custom system prompts and agent instructions tailored to your business needs. Initiate single calls or start high-volume campaigns with up to 100,000 contacts per batch with intelligent rate limiting. Track total agents, active calls, lead conversions, and daily call durations with detailed transcription and sentiment analysis. Configurable retry strategies for busy signals and no-answers to maximize connectivity and conversion rates. ## Getting Started Ready to start making calls? Follow our quickstart guide to get up and running. Set up your first agent and make your first call in minutes. Explore our API to programmatically integrate Dialgen into your existing CRM or workflow. ## Why Dialgen? Traditional call centers face challenges with scalability, consistency, and wait times. Dialgen solves these by providing: * **Instant Scalability**: Go from 1 call to 10,000 calls instantly. * **24/7 Availability**: Your agents are always ready, never tired, and never take a break. * **Consistent Quality**: Every call follows your brand guidelines and provides a superior customer experience. * **Data-Driven Insights**: Every interaction is transcribed and analyzed, providing you with deep insights into your customer base. # Quickstart Source: https://docs.dialgen.ai/quickstart Get started with Dialgen in minutes. ## Get Started with Dialgen This guide will help you make your first AI-powered voice call using the Dialgen API. ### Step 1: Obtain Your API Key All requests to the Dialgen API require authentication with a Bearer Token. You can generate and manage your API keys at [sa.dialgen.ai/api-keys](https://sa.dialgen.ai/api-keys). Once generated, keep it secure. ### Step 2: Make Your First Call Use the `Start a Single Call` endpoint to initiate an outbound call. Replace `YOUR_API_KEY` with your actual API key and adjust the `to`, `agentConfigId`, and `userId` fields as necessary. You can find your `userId` in the [sa.dialgen.ai](https://sa.dialgen.ai) dashboard. ```bash theme={null} curl -X POST https://sa.dialgen.ai/api/v1/call/dial \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "to": "+1234567890", "agentConfigId": "agent_123", "userId": "YOUR_USER_ID", "callerDetails": { "name": "John Doe", "email": "john.doe@example.com" } }' ``` Upon success, you will receive a `callId` which you can use to monitor the call's status. ### Step 3: Explore the API Now that you've made your first call, you can explore other functionalities: * **Monitor Call Status:** Check the live status of your calls. * **Create Batch Campaigns:** Initiate high-volume call campaigns. * **Retrieve Call Metrics:** Get detailed analytics and summaries for completed calls. For more details on these and other endpoints, refer to the [API Reference](/api-reference/introduction).