> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chatbotplatform.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Async Replies

> Handle long-running operations with asynchronous responses

Async replies allow your integration to acknowledge a message immediately and send the final response later. This is essential for operations that take longer than the webhook timeout or require background processing.

## Overview

Standard webhook flow has a timeout (default 30 seconds). If your processing takes longer, use async replies:

**Standard Flow**:

```
User sends message → Bot calls integration → Integration responds → Bot sends response
[Must complete within timeout]
```

**Async Flow**:

```
User sends message → Bot calls integration → Integration returns "Processing..."
                                           → Bot sends interim message
[Later]
Integration completes → Calls Conversation Messages API → Bot sends final response
```

## When to Use Async Replies

### Good Use Cases

> [card] Long Processing
>
> AI operations taking >30 seconds

> [card] External APIs
>
> Waiting for slow third-party services

> [card] Complex Workflows
>
> Multi-step processes with user updates

> [card] Background Jobs
>
> Queued tasks processed later

### Examples

* **AI Image Generation**: "I'm generating your image. This will take about 2 minutes..."
* **Data Analysis**: "I'm analyzing your file. I'll send the results shortly..."
* **External Lookups**: "I'm checking our inventory system. One moment..."
* **Report Generation**: "I'm creating your report. I'll notify you when it's ready..."

## Implementation

### Step 1: Immediate Acknowledgment

Return an immediate response with `async: true`:

```json theme={null}
{
  "content": "I'm processing your request. This may take a few minutes...",
  "async": true
}
```

The bot sends this message to the user immediately.

### Step 2: Background Processing

Your backend processes the request asynchronously:

```javascript theme={null}
// Example with job queue
app.post('/webhook', async (req, res) => {
  const { messages, conversation_id, user } = req.body;

  // Return immediate acknowledgment
  res.json({
    content: "I'm generating your image. This will take about 2 minutes...",
    async: true
  });

  // Queue background job
  await jobQueue.add('generate-image', {
    conversationId: conversation_id,
    prompt: messages[messages.length - 1].content,
    userId: user.id
  });
});
```

### Step 3: Send Final Response

When processing completes, send the final response via the Conversation Messages API:

```javascript theme={null}
// Background job handler
async function handleImageGeneration(job) {
  const { conversationId, prompt } = job.data;

  // Generate image (takes 2+ minutes)
  const imageUrl = await generateImage(prompt);

  // Send final response via API
  await fetch('https://api.chatbotplatform.io/v1/conversations/{conversationId}/messages', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      content: `Here's your generated image: ${imageUrl}`,
      role: 'assistant'
    })
  });
}
```

## Conversation Messages API

### Send Message

**Endpoint**: `POST /v1/conversations/{conversation_id}/messages`

**Authentication**: Bearer token (API key)

**Request Body**:

```json theme={null}
{
  "content": "The final response message",
  "role": "assistant",
  "metadata": {
    "async": true,
    "processing_time": 125000,
    "custom_field": "value"
  }
}
```

**Response**:

```json theme={null}
{
  "id": "msg_abc123",
  "conversation_id": "conv_xyz789",
  "role": "assistant",
  "content": "The final response message",
  "created_at": "2024-01-15T10:35:00Z"
}
```

### Code Examples

> [accordion] Send async reply
>
> > [tab] cURL
> >
> > ```bash theme={null}
> > curl -X POST https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages \
> >   -H "Authorization: Bearer YOUR_API_KEY" \
> >   -H "Content-Type: application/json" \
> >   -d '{
> >     "content": "Here is your completed report: https://example.com/report.pdf",
> >     "role": "assistant"
> >   }'
> > ```
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > const response = await fetch('https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages', {
> >   method: 'POST',
> >   headers: {
> >     'Authorization': 'Bearer YOUR_API_KEY',
> >     'Content-Type': 'application/json'
> >   },
> >   body: JSON.stringify({
> >     content: 'Here is your completed report: https://example.com/report.pdf',
> >     role: 'assistant'
> >   })
> > });
> >
> > const message = await response.json();
> > console.log('Message sent:', message.id);
> > ```
>
> > [tab] PHP
> >
> > ```php theme={null}
> > use Illuminate\Support\Facades\Http;
> >
> > $response = Http::withToken('YOUR_API_KEY')
> >     ->post('https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages', [
> >         'content' => 'Here is your completed report: https://example.com/report.pdf',
> >         'role' => 'assistant'
> >     ]);
> >
> > $message = $response->json();
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > import requests
> >
> > response = requests.post(
> >     'https://api.chatbotplatform.io/v1/conversations/conv_abc123/messages',
> >     headers={'Authorization': 'Bearer YOUR_API_KEY'},
> >     json={
> >         'content': 'Here is your completed report: https://example.com/report.pdf',
> >         'role': 'assistant'
> >     }
> > )
> >
> > message = response.json()
> > print(f"Message sent: {message['id']}")
> > ```

> [accordion] Send multiple updates
>
> > [tab] JavaScript
> >
> > ```javascript theme={null}
> > // Send progress updates
> > async function sendProgressUpdates(conversationId) {
> >   // Update 1
> >   await fetch(`https://api.chatbotplatform.io/v1/conversations/${conversationId}/messages`, {
> >     method: 'POST',
> >     headers: {
> >       'Authorization': 'Bearer YOUR_API_KEY',
> >       'Content-Type': 'application/json'
> >     },
> >     body: JSON.stringify({
> >       content: '25% complete - Processing images...',
> >       role: 'assistant'
> >     })
> >   });
> >
> >   // Update 2
> >   await fetch(`https://api.chatbotplatform.io/v1/conversations/${conversationId}/messages`, {
> >     method: 'POST',
> >     headers: {
> >       'Authorization': 'Bearer YOUR_API_KEY',
> >       'Content-Type': 'application/json'
> >     },
> >     body: JSON.stringify({
> >       content: '75% complete - Generating report...',
> >       role: 'assistant'
> >     })
> >   });
> >
> >   // Final result
> >   await fetch(`https://api.chatbotplatform.io/v1/conversations/${conversationId}/messages`, {
> >     method: 'POST',
> >     headers: {
> >       'Authorization': 'Bearer YOUR_API_KEY',
> >       'Content-Type': 'application/json'
> >     },
> >     body: JSON.stringify({
> >       content: '✅ Complete! Here is your report: https://example.com/report.pdf',
> >       role: 'assistant'
> >     })
> >   });
> > }
> > ```
>
> > [tab] Python
> >
> > ```python theme={null}
> > def send_progress_updates(conversation_id):
> >     headers = {'Authorization': 'Bearer YOUR_API_KEY'}
> >     base_url = f'https://api.chatbotplatform.io/v1/conversations/{conversation_id}/messages'
> >
> >     # Update 1
> >     requests.post(
> >         base_url,
> >         headers=headers,
> >         json={
> >             'content': '25% complete - Processing images...',
> >             'role': 'assistant'
> >         }
> >     )
> >
> >     # Update 2
> >     requests.post(
> >         base_url,
> >         headers=headers,
> >         json={
> >             'content': '75% complete - Generating report...',
> >             'role': 'assistant'
> >         }
> >     )
> >
> >     # Final result
> >     requests.post(
> >         base_url,
> >         headers=headers,
> >         json={
> >             'content': '✅ Complete! Here is your report: https://example.com/report.pdf',
> >             'role': 'assistant'
> >         }
> >     )
> > ```

## Advanced Patterns

### Progress Updates

Send multiple updates as work progresses:

```javascript theme={null}
app.post('/webhook', async (req, res) => {
  const { conversation_id, messages } = req.body;

  res.json({
    content: "I'm starting to process your video. This will take several minutes...",
    async: true
  });

  processVideoWithUpdates(conversation_id, messages);
});

async function processVideoWithUpdates(conversationId, messages) {
  const stages = [
    { percent: 25, message: '25% - Analyzing video...' },
    { percent: 50, message: '50% - Extracting frames...' },
    { percent: 75, message: '75% - Generating summary...' },
    { percent: 100, message: '✅ Complete! Here is your video summary.' }
  ];

  for (const stage of stages) {
    await processStage(stage.percent);

    await sendMessage(conversationId, stage.message);
  }
}
```

### Error Handling

Handle errors gracefully during async processing:

```javascript theme={null}
async function processRequestAsync(conversationId, data) {
  try {
    const result = await longRunningOperation(data);

    await sendMessage(conversationId, {
      content: `✅ Success! ${result.summary}`,
      metadata: { success: true }
    });
  } catch (error) {
    console.error('Async processing error:', error);

    await sendMessage(conversationId, {
      content: `❌ Sorry, I encountered an error: ${error.message}. Please try again.`,
      metadata: { success: false, error: error.message }
    });
  }
}
```

### Timeout and Retries

Implement retries for API calls:

```javascript theme={null}
async function sendMessageWithRetry(conversationId, content, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const response = await fetch(
        `https://api.chatbotplatform.io/v1/conversations/${conversationId}/messages`,
        {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${process.env.API_KEY}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            content: content,
            role: 'assistant'
          })
        }
      );

      if (response.ok) {
        return await response.json();
      }

      // If not successful and not last attempt, wait and retry
      if (attempt < maxRetries) {
        await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
      }
    } catch (error) {
      if (attempt === maxRetries) {
        throw error;
      }
      await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
    }
  }

  throw new Error('Failed to send message after retries');
}
```

### Job Queue Pattern

Use a job queue for reliable async processing:

```javascript theme={null}
// Using Bull Queue (Redis-based)
const Queue = require('bull');
const processQueue = new Queue('process-requests', 'redis://localhost:6379');

// Webhook handler
app.post('/webhook', async (req, res) => {
  const { conversation_id, messages, user } = req.body;

  // Add job to queue
  await processQueue.add({
    conversationId: conversation_id,
    messages: messages,
    user: user
  });

  // Return immediate response
  res.json({
    content: "I've received your request and I'm processing it now...",
    async: true
  });
});

// Job processor
processQueue.process(async (job) => {
  const { conversationId, messages, user } = job.data;

  try {
    // Long-running operation
    const result = await complexProcessing(messages);

    // Send final response
    await sendMessage(conversationId, result);
  } catch (error) {
    await sendMessage(conversationId, `Error: ${error.message}`);
  }
});
```

## User Experience Best Practices

### Clear Communication

Set clear expectations in the interim message:

**Good**:

* "I'm generating your report. This will take about 2-3 minutes..."
* "Processing your video (typically takes 5 minutes)..."
* "Analyzing your data. I'll send results in about 30 seconds..."

**Bad**:

* "Please wait..."
* "Processing..."
* "Working on it"

### Reasonable Timeouts

Don't make users wait too long. If processing takes >5 minutes, consider:

* Email notification instead
* Webhook callback to user
* Dashboard where users can check status

**Recommended Maximum Wait Times**:

| Use Case | Max Wait | User Experience |
| - | - | - |
| Text generation | 2 minutes | Good |
| Image generation | 5 minutes | Acceptable |
| Video processing | 10 minutes | Poor - consider email |
| Large file analysis | 15 minutes | Poor - use dashboard |

### Progress Indicators

If processing is long, send progress updates:

```
Initial: "I'm processing your video..."
25%: "25% complete - Analyzing frames..."
50%: "50% complete - Extracting audio..."
75%: "75% complete - Generating summary..."
100%: "✅ Done! Here's your video summary: ..."
```

## Security Considerations

### API Key Security

> [card] Server-Side Only
>
> Never expose API keys in client-side code

> [card] Environment Variables
>
> Store keys in environment variables

> [card] Rotate Regularly
>
> Rotate API keys periodically

> [card] Least Privilege
>
> Use keys with minimum required permissions

### Conversation ID Validation

Always validate the conversation ID before sending messages:

```javascript theme={null}
async function sendMessage(conversationId, content) {
  // Validate conversation exists and belongs to your bot
  const conversation = await fetch(
    `https://api.chatbotplatform.io/v1/conversations/${conversationId}`,
    {
      headers: { 'Authorization': `Bearer ${process.env.API_KEY}` }
    }
  );

  if (!conversation.ok) {
    throw new Error('Invalid conversation ID');
  }

  // Send message
  await fetch(
    `https://api.chatbotplatform.io/v1/conversations/${conversationId}/messages`,
    {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ content, role: 'assistant' })
    }
  );
}
```

## Troubleshooting

### Messages Not Appearing

**Check**:

* Conversation ID is correct
* API key has proper permissions
* Response status is 200 OK
* User hasn't blocked the bot
* Channel is still connected

### Duplicate Messages

**Causes**:

* Job processed multiple times
* Retry logic without idempotency
* Multiple workers processing same job

**Solution**:

```javascript theme={null}
// Add idempotency key
await fetch(url, {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
    'Idempotency-Key': `job-${jobId}` // Prevents duplicates
  },
  body: JSON.stringify({ content, role: 'assistant' })
});
```

### Rate Limiting

**Problem**: Too many API calls in short time

**Solution**:

* Implement exponential backoff
* Queue messages locally
* Batch updates when possible
* Respect rate limits

> [card] [Complete API Reference](https://app.chatbotplatform.io/openapi)
>
> View the full API specification with all endpoints, parameters, and response schemas.

## Next Steps

> [card] [Webhook Payload](https://docs.chatbotplatform.io/bots/integrations/webhook-payload.md)
>
> Understand the payload format

> [card] [Conversation API](https://docs.chatbotplatform.io/bots/conversations/api.md)
>
> Explore conversation management

> [card] [Webhook Setup](https://docs.chatbotplatform.io/bots/integrations/webhook-setup)
>
> Configure your integration


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.