npm package: @saulo.martins/chat.api
Description: Express chat API with Supabase, OpenAI and rate limiting
Latest version: 1.2.0

# chat-api

Express chat API with Supabase (conversations + messages + system prompt table), OpenAI, and rate limiting. Mount in your app or run standalone. Use with [chat](https://github.com/saulommartins/chat) on the frontend.

## Install

```bash
npm install chat-api
# or from Git
npm install git+ssh://git@github.com:saulommartins/chat.api.git
```

## Database (Supabase)

Run the migrations in your Supabase SQL Editor (in order):

1. `migrations/01-conversations-messages.sql` — creates `conversations` and `messages`
2. `migrations/02-chat_system_prompt.sql` — creates `chat_system_prompt` (single row, id=1). Edit the row content to set your assistant behavior and optional WhatsApp link.

## Mount in your Express app

```js
const express = require('express');
const { createClient } = require('@supabase/supabase-js');
const { createChatRouter } = require('chat-api');

const supabase = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_SERVICE_KEY
);

const chatRouter = createChatRouter({
  supabase,
  openaiApiKey: process.env.OPENAI_API_KEY,
  rateLimitWindowMs: Number(process.env.RATE_LIMIT_CHAT_WINDOW_MS) || 60000,
  rateLimitMax: Number(process.env.RATE_LIMIT_CHAT_MAX) || 10,
  // optional: rateLimitMessage, conversationsTable, messagesTable, systemPromptTable, openaiModel, openaiMaxTokens, openaiTemperature
});

const app = express();
app.use(express.json());
app.use('/api/chat', chatRouter);
```

## Options (ChatApiOptions)

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `supabase` | SupabaseClient | **required** | Supabase client (service role). |
| `openaiApiKey` | string | **required** | OpenAI API key. |
| `rateLimitWindowMs` | number | 60000 | Rate limit window (ms). |
| `rateLimitMax` | number | 10 | Max POST requests per window per IP. |
| `rateLimitMessage` | string | (en) | JSON message when limit exceeded. |
| `conversationsTable` | string | conversations | Table name. |
| `messagesTable` | string | messages | Table name. |
| `systemPromptTable` | string | chat_system_prompt | Table name (single row, id=1). |
| `openaiModel` | string | gpt-3.5-turbo | OpenAI model. |
| `openaiMaxTokens` | number | 500 | Max tokens per reply. |
| `openaiTemperature` | number | 0.7 | Temperature. |

## API contract

- **POST /api/chat** — Body: `{ message: string, conversationId?: string, visitorId?: string, visitorLabel?: string }`. Returns `{ conversationId, reply, message }`. Rate limited. Optional `visitorId` / `visitorLabel` aparecem nas notificações WhatsApp (wp.api), junto com IP e User-Agent.
- **GET /api/chat/:conversationId** — Returns `{ conversationId, messages }`.

## Notificações WhatsApp (opcional)

Com `WP_API_URL`, `WP_API_PUBLIC_KEY`, `WP_API_SECRET_KEY` e `WHATSAPP_NOTIFY_TO` (igual ao 2-vision-api), cada mensagem do visitante e cada resposta da IA geram um envio para o wp.api. O texto inclui identificadores (conversa, visitante, remetente, IP, UA). `CHAT_NOTIFY_SOURCE` customiza a primeira linha (ex.: site/marca).

## Repo

<https://github.com/saulommartins/chat.api>