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

# Subscribe to stream

> Subscreve um stream de chat ativo para receberes respostas da IA em tempo real

Subscreve um stream de chat ativo para receberes respostas da IA em tempo real. É uma alternativa a acompanhar o endpoint [Get status](/docs/pt/api/get-status).

## Pedido

```
GET /api/chat/{chatId}/subscribe
```

### Cabeçalhos

| Cabeçalho | Obrigatório | Descrição |
| - | - | - |
| `Authorization` | Sim | `Bearer macaly_...` |

### Parâmetros de caminho

| Parâmetro | Tipo | Descrição |
| - | - | - |
| `chatId` | string | O ID do chat devolvido por `POST /api/chat` |

### Exemplo de pedido

<CodeGroup>
  ```bash cURL theme={null}
  curl -N https://www.macaly.com/api/chat/abc123/subscribe \
    -H "Authorization: Bearer macaly_abc123..."
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    `https://www.macaly.com/api/chat/${chatId}/subscribe`,
    {
      headers: {
        'Authorization': 'Bearer macaly_abc123...',
      },
    }
  );

  if (response.status === 204) {
    console.log('No active stream');
    return;
  }

  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    const chunk = decoder.decode(value);
    for (const line of chunk.split('\n')) {
      if (line.startsWith('0:')) {
        // Text content
        const text = JSON.parse(line.slice(2));
        process.stdout.write(text);
      }
    }
  }
  ```

  ```python Python theme={null}
  import requests

  response = requests.get(
      f'https://www.macaly.com/api/chat/{chat_id}/subscribe',
      headers={
          'Authorization': 'Bearer macaly_abc123...',
      },
      stream=True,
  )

  if response.status_code == 204:
      print('No active stream')
  else:
      for line in response.iter_lines():
          if line:
              line = line.decode('utf-8')
              if line.startswith('0:'):
                  import json
                  text = json.loads(line[2:])
                  print(text, end='')
  ```
</CodeGroup>

## Resposta

Devolve um stream de Server-Sent Events (SSE) com o progresso do processamento e as respostas da IA.

### Formato do stream

O stream usa o protocolo de data stream do [Vercel AI SDK v4](https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol#data-stream-protocol). Cada fragmento tem um prefixo com um indicador de tipo:

| Prefixo | Descrição |
| - | - |
| `0:` | Conteúdo de texto |
| `2:` | Objetos de dados (como `{ chatId }`) |
| `8:` | Anotações e metadados |

### Exemplo de stream

```
2:[{"chatId":"abc123"}]
0:"I'll create a landing page for you."
0:" Let me start by setting up the project structure."
8:{"type":"tool-call","toolName":"WriteFile",...}
0:" Done! Your landing page is ready."
```

## Códigos de estado

| Estado | Descrição |
| - | - |
| 200 | Sucesso (resposta em stream) |
| 204 | Nenhum stream ativo (processamento concluído ou não iniciado) |
| 401 | Chave API inválida ou em falta |
| 403 | O chat não pertence à tua equipa |
| 404 | Chat não encontrado |
| 429 | Limite de pedidos atingido |

## Notas

* O stream termina quando o processamento é concluído
* Se chamares este endpoint depois de o processamento ter terminado, recebes uma resposta `204 No Content`
* Para implementações mais simples, considera acompanhar o endpoint [Get status](/docs/pt/api/get-status)


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