# Chat API

> Answers questions from a bot's indexed website content (RAG) and streams the answer with sources. Server-to-server only: call it from your own backend with a secret API key.

## Conversation endings

POST https://aiduko.com/api/v1/chat/end with JSON { "id": "chat-123", "reason": "explicit" } (or "reset" for a new conversation). Use the same Authorization header and API key as the chat. Returns 200 { "ok": true }, including already-ended or unknown ids. Validation errors use 400 invalid_request, invalid keys 401 invalid_api_key, and rate limits 429 rate_limited with Retry-After. End requests remain available while answering is paused or the token budget is exhausted.

Send an end request before clearing chat history or starting a new conversation. In-flight answers settle before finalization. An inactivity timeout (30 minutes by default, configurable by the owner) catches closed tabs, lost connections and clients that never send end requests. Minimize, answer completion, and transient errors do not immediately end a chat. A request using an ended id starts a fresh stored session. Anonymous visitors are not emailed: opted-in team members receive a dashboard link at their verified account email.

## Retention

GET https://aiduko.com/api/v1/chat/policy with the same Authorization header returns 200 `{ "retentionDays": 90 }`: the number of days after the last question that the bot owner's team keeps a chat's questions and answers (30, 90, 180 or 365, chosen by the team; 90 by default). Show it in the notice next to the chat. The value can change at any time and the endpoint counts against the key's rate limit (401 invalid_api_key, 429 rate_limited with Retry-After), so cache it on your server for a few minutes instead of calling it per page view.

## Authentication

Send `Authorization: Bearer nsk_ai_…`. Create keys in the dashboard (bot page → API). Keys are shown once and stored hashed. Each key has a rate limit per minute and a monthly token budget.

## POST https://aiduko.com/api/v1/chat

Request body (JSON), compatible with `useChat` / `Chat` from `@ai-sdk/vue`:

```json
{ "id": "chat-123", "messages": [{ "id": "1", "role": "user", "parts": [{ "type": "text", "text": "What does the Pro plan cost?" }] }] }
```

- 1 to 40 messages (the conversation history), roles `user` and `assistant`; other roles and non-text parts are ignored
- a user message at most 4000 characters, an assistant message at most 12000, all messages together at most 100000 (text of all parts); at most 50 parts per message; the last message must be a user message with text
- answers have at most 1500 output tokens
- follow-up questions are rewritten using the history before searching
- `id` (optional, at most 200 characters): the chat id. Questions and answers are stored for the bot owner's chat history, grouped by this id

Response: `text/event-stream` in the AI SDK UI message stream protocol. Relevant parts:

- `text-delta`: answer text (Markdown). Citations look like `[1]` or `[2][3]`.
- `source-url`: `{ sourceId, url, title }`, one per web page the model saw. `sourceId` is the citation number.
- `source-document`: `{ sourceId, title, filename, mediaType }` for pages of uploaded documents (PDF, Word, PowerPoint, Markdown, text). The title names the file and page, e.g. `Handbook.pdf › Page 4`. There is no URL: the original files are private, so show the title as plain text.
- `finish` with `messageMetadata.usage`: `{ inputTokens, outputTokens, model }`

If no indexed content is relevant, the answer says so and there are no source parts.

## Errors

JSON `{ "error": { "code": string, "message": string } }`:

- 400 `invalid_request`, `invalid_messages`, `message_too_long`, `answer_too_long`, `conversation_too_long`, `too_many_parts`, `no_question`
- 401 `invalid_api_key` (missing, unknown or revoked)
- 429 `rate_limited` (see the `Retry-After` header) `budget_exceeded` (the key's monthly token budget is used up) or `plan_limit_reached` (the team's monthly tokens of its plan are used up)

Budgets are checked before the answer: each request reserves its estimated tokens (history, sources and the longest possible answer) in the key's and the team's monthly budget, and parallel requests can't spend the same remaining tokens. Once the answer is done, failed or cancelled, the reservation is replaced by the tokens actually used. Near the end of a budget, a request can therefore get `budget_exceeded` or `plan_limit_reached` although a few tokens are left.

## MCP server

https://aiduko.com/api/v1/mcp is a Model Context Protocol server (Streamable HTTP, stateless, JSON responses) for the bot of the API key. Send the same `Authorization: Bearer nsk_ai_…` header; MCP clients such as Claude Code, Claude Desktop (via mcp-remote) and Cursor connect with the URL and that header. Every POST carries JSON-RPC (up to 10 messages); GET and DELETE return 405.

Tools:

- `ask` `{ question: string, conversation_id?: string }`: a grounded answer with `[n]` citations and the source URLs below it (`structuredContent: { answer, conversation_id, sources: [{ id, title, url }] }`). Without sources when the owner hides them. Answers appear in the owner's chat history (channel MCP), grouped by `conversation_id`.
- `search` `{ query: string, limit?: 1–10 }`: the best-matching passages with their URLs, without an answer. Only listed when the bot shows its sources.

Tool calls count against the key's rate limit and monthly budget and the team's monthly tokens, like chat requests. Limits and pauses come back as tool results with `isError: true` and a code: `rate_limited`, `budget_exceeded`, `plan_limit_reached`, `chat_paused`, `invalid_arguments`. A missing, unknown or revoked key gets HTTP 401.

## Integrating into a Nuxt app

Add a server route that forwards `{ id, messages }` with the key from the server env and returns the upstream response unchanged; use `DefaultChatTransport({ api: '/api/chat' })` on the client. All visitors share one key: use an atomic per-visitor rate limit in shared storage with expiring counters, returning 503 without an API call if storage fails. Use the socket peer IP unless an explicitly trusted proxy overwrites X-Forwarded-For with one visitor IP and the origin is restricted to that proxy. Bound the upstream lifetime including streaming and abort on visitor disconnect.

The following illustrates forwarding only. Before exposing it publicly, add input validation, the shared visitor limiter, trusted-proxy configuration, and timeout/disconnect cancellation. The complete Nuxt reference integration includes these protections.

```ts
// server/api/chat.post.ts
export default defineEventHandler(async (event) => {
  const { id, messages } = await readBody(event)
  const { chatbotApiKey, chatbotApiUrl } = useRuntimeConfig(event)
  return fetch(chatbotApiUrl, {
    body: JSON.stringify({ id, messages }),
    headers: { 'authorization': `Bearer ${chatbotApiKey}`, 'content-type': 'application/json' },
    method: 'POST',
  })
})
```

- OpenAPI: https://aiduko.com/api/v1/openapi.json
