> ## 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.

# Create chat

> Cria uma nova sessão de chat e começa a construir com IA

Cria uma nova sessão de chat e inicia o workflow da IA.

## Requisição

```
POST /api/chat
```

### Cabeçalhos

| Cabeçalho | Obrigatório | Descrição |
| - | - | - |
| `Authorization` | Sim | `Bearer macaly_...` |
| `Content-Type` | Sim | `application/json` |

### Parâmetros do corpo

| Campo | Tipo | Obrigatório | Padrão | Descrição |
| - | - | - | - | - |
| `content` | string | Sim | - | A mensagem (prompt) do usuário |
| `stream` | boolean | Não | `true` | Se `false`, retorna JSON em vez de stream |
| `backend` | string | Não | `"DEFAULT"` | Backend a ser usado |
| `executionMode` | `"auto"` \| `"planning"` \| `"build"` | Não | - | Define como a IA aborda a tarefa |
| `model` | `"gpt-5.6-terra"` \| `"gpt-6.1-sol"` \| `"gpt-6-luna"` \| `"grok-4-6"` \| `"kimi-k3"` \| `"sonnet-5-5"` \| `"opus-5-5"` \| `"blueai-glm-5-3"` \| `"blueai-glm-5-3-flash"` | Não | - | Modelo de IA a ser usado. Se omitido, vale o modelo configurado no workspace |
| `reasoningEffort` | `"medium"` \| `"high"` | Não | - | Define o quanto a IA aprofunda o raciocínio sobre a tarefa |
| `experimental_attachments` | array | Não | `[]` | Anexos de arquivo (formato abaixo) |

#### Formato dos anexos

Cada item do array `experimental_attachments` tem a seguinte estrutura:

| Campo | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `url` | string | Sim | URL do arquivo a ser anexado |
| `name` | string | Não | Nome de exibição do anexo |
| `contentType` | string | Não | Tipo MIME do arquivo |

### Exemplo de requisição

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://www.macaly.com/api/chat \
    -H "Authorization: Bearer macaly_abc123..." \
    -H "Content-Type: application/json" \
    -d '{
      "content": "Create a landing page for a coffee shop",
      "stream": false
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://www.macaly.com/api/chat', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer macaly_abc123...',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      content: 'Create a landing page for a coffee shop',
      stream: false,
    }),
  });

  const data = await response.json();
  console.log(data.chatId);
  ```

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

  response = requests.post(
      'https://www.macaly.com/api/chat',
      headers={
          'Authorization': 'Bearer macaly_abc123...',
          'Content-Type': 'application/json',
      },
      json={
          'content': 'Create a landing page for a coffee shop',
          'stream': False,
      },
  )

  data = response.json()
  print(data['chatId'])
  ```
</CodeGroup>

## Resposta

### Resposta JSON (com `stream: false`)

```json theme={null}
{
  "chatId": "abc123def456",
  "url": "https://www.macaly.com/chat/abc123def456",
  "streamId": "stream_xyz789",
  "assistantMessageId": "msg_123"
}
```

| Campo | Tipo | Descrição |
| - | - | - |
| `chatId` | string | Identificador único do chat |
| `url` | string | Link direto para ver o chat |
| `streamId` | string \| undefined | Identificador do stream para assinatura. Presente apenas em backends com workflow |
| `assistantMessageId` | string \| undefined | ID da mensagem do assistente em geração. Presente apenas em backends com workflow |

### Resposta em streaming (com `stream: true`, o padrão)

Com o streaming ativado, a resposta é um stream de texto:

```
2:[{"chatId":"abc123def456"}]
0:"Starting to build..."
...
```

A primeira linha contém o ID do chat no formato `2:[{"chatId":"..."}]`.

#### Extraindo o ID do chat do stream

```javascript theme={null}
const text = await response.text();
const match = text.match(/2:\[{"chatId":"([^"]+)"/);
const chatId = match?.[1];
```

## Códigos de status

| Código | Descrição |
| - | - |
| 200 | Sucesso: chat criado |
| 400 | Corpo da requisição inválido |
| 401 | Chave de API inválida ou ausente |
| 402 | Créditos insuficientes |
| 403 | Forbidden: sem permissão para o workspace informado |
| 422 | Erro de validação |
| 429 | Limite de requisições excedido |
| 500 | Erro no servidor |

## Próximos passos

Depois de criar o chat:

1. **Acompanhe a conclusão** com [`GET /api/chat/{chatId}/status`](/docs/pt-BR/api/get-status)
2. **Assine o stream** com [`GET /api/chat/{chatId}/subscribe`](/docs/pt-BR/api/subscribe-stream) para receber atualizações em tempo real
3. **Envie mensagens de acompanhamento** com [`POST /api/chat/{chatId}/publish`](/docs/pt-BR/api/publish-message)


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