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

# Real-time Stream

> SSE connection for real-time updates

## Endpoint

<Card>
  <strong>GET</strong> `/backend/conversations/stream`
</Card>

This endpoint uses **Server-Sent Events (SSE)** for real-time communication.

## Connection

```javascript theme={null}
const eventSource = new EventSource(
  'https://api.leavo.ai/backend/conversations/stream',
  {
    headers: {
      'Authorization': 'Bearer your_api_key_here'
    }
  }
);

eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Event received:', data);
};

eventSource.onerror = (error) => {
  console.error('Connection error:', error);
};
```

## Event Types

### new\_message

New message received or sent.

```json theme={null}
{
  "type": "new_message",
  "data": {
    "conversation_id": "uuid",
    "message": {
      "id": "message-uuid",
      "content": "Hello!",
      "role": "user",
      "timestamp": "2024-01-15T14:30:00Z"
    }
  }
}
```

### typing

Lead is typing.

```json theme={null}
{
  "type": "typing",
  "data": {
    "conversation_id": "uuid",
    "lead_id": "lead-uuid"
  }
}
```

### status\_change

Conversation status changed.

```json theme={null}
{
  "type": "status_change",
  "data": {
    "conversation_id": "uuid",
    "status": "archived"
  }
}
```

## Best Practices

<CardGroup cols={2}>
  <Card title="Reconnection" icon="rotate">
    Implement automatic reconnection logic in case of disconnection.
  </Card>

  <Card title="Heartbeat" icon="heart-pulse">
    The server sends heartbeat events every 30 seconds to keep the connection alive.
  </Card>

  <Card title="Authentication" icon="key">
    The token is validated on initial connection. Connections with invalid tokens are rejected.
  </Card>

  <Card title="Fallback" icon="arrows-rotate">
    Have a fallback with periodic polling in case SSE is not supported.
  </Card>
</CardGroup>

## Complete Example

```javascript theme={null}
class ConversationStream {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.eventSource = null;
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
  }

  connect() {
    this.eventSource = new EventSource(
      `https://api.leavo.ai/backend/conversations/stream?token=${this.apiKey}`
    );

    this.eventSource.onopen = () => {
      console.log('Connected');
      this.reconnectAttempts = 0;
    };

    this.eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data);
      this.handleEvent(data);
    };

    this.eventSource.onerror = () => {
      this.eventSource.close();
      this.reconnect();
    };
  }

  handleEvent(data) {
    switch (data.type) {
      case 'new_message':
        this.onNewMessage(data.data);
        break;
      case 'typing':
        this.onTyping(data.data);
        break;
    }
  }

  reconnect() {
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++;
      const delay = Math.pow(2, this.reconnectAttempts) * 1000;
      setTimeout(() => this.connect(), delay);
    }
  }

  disconnect() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  }

  // Override these methods
  onNewMessage(data) {}
  onTyping(data) {}
}
```
