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

# Build your own chat UI

> Put your AI agent in your own app's chat, with streamed progress, citations, ratings, and a handoff to your team.

This guide builds a chat experience like the [chat widget](https://docs.decimal.app/chat-widgets/overview.md), but in your own interface. If the widget's look and layout options are enough, [install the widget](https://docs.decimal.app/chat-widgets/installation.md) instead. It takes minutes.

By the end, your chat will:

* Send a customer's question and show what the agent is doing while it works
* Show the answer with its citations
* Take follow-up questions in the same conversation
* Let the customer rate an answer
* Hand the conversation to your helpdesk when the customer needs a person

## How the pieces fit

```
Browser  ──▶  Your server  ──▶  api.getdecimal.ai
```

Your API token can read every conversation in your organization, so it stays on your server. The browser talks only to your server. Your server checks who the customer is, adds the token, and passes the request on to Decimal.

Your server also decides which conversations each customer may see. Decimal knows the conversation, not your customer, so record which of your users started each `conversation_id` and refuse any other user's.

## 1. Create a token

Open **Settings → API Keys** and create a token with these [scopes](https://docs.decimal.app/api-reference/authentication.md#scopes):

| Scope | For |
| - | - |
| `chat:write` | Sending messages and rating answers |
| `chat:read` | Loading a conversation |
| `chat:escalate` | Handing a conversation to your helpdesk |

Leave out `chat:escalate` if you won't offer a handoff. Store the token as a server environment variable, such as `DECIMAL_API_KEY`.

To offer a handoff, also [connect your helpdesk](https://docs.decimal.app/api-reference/escalation/overview.md#before-you-escalate).

## 2. Proxy messages through your server

Send messages with `stream: true`. The answer then comes back over the same connection as [server-sent events](#3-read-the-stream-in-the-browser), so you don't have to poll.

This Next.js route handler forwards a message and streams the events back to the browser. `getSignedInUser`, `ownsConversation`, and `saveConversation` stand for your own auth and storage.

```ts app/api/support-chat/route.ts theme={null}
const DECIMAL_API = 'https://api.getdecimal.ai/v0';

export async function POST(req: Request) {
  const user = await getSignedInUser(req);
  if (!user) {
    return new Response(null, { status: 401 });
  }

  const { message, conversationId, idempotencyKey } = await req.json();
  if (conversationId && !(await ownsConversation(user.id, conversationId))) {
    return new Response(null, { status: 404 });
  }

  const upstream = await fetch(`${DECIMAL_API}/chat`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.DECIMAL_API_KEY}`,
      'Content-Type': 'application/json',
      'Idempotency-Key': idempotencyKey,
    },
    body: JSON.stringify({
      message,
      conversation_id: conversationId,
      stream: true,
      user: { name: user.name, email: user.email },
    }),
  });

  const contentType = upstream.headers.get('Content-Type') ?? 'application/json';
  if (!upstream.ok || !contentType.startsWith('text/event-stream') || !upstream.body) {
    return new Response(upstream.body, { status: upstream.status, headers: { 'Content-Type': contentType } });
  }

  const [toBrowser, toInspect] = upstream.body.tee();
  if (!conversationId) {
    void recordNewConversation(toInspect, user.id);
  } else {
    void toInspect.cancel();
  }

  return new Response(toBrowser, {
    headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' },
  });
}

async function recordNewConversation(stream: ReadableStream<Uint8Array>, userId: string) {
  const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
  let buffer = '';
  while (!buffer.includes('\n\n')) {
    const { value, done } = await reader.read();
    if (done) return;
    buffer += value;
  }
  const data = buffer.split('\n').find((line) => line.startsWith('data: '));
  if (data) {
    const { conversation_id } = JSON.parse(data.slice('data: '.length));
    await saveConversation(userId, conversation_id);
  }
  await reader.cancel();
}
```

The first event is always `message.started`, which carries the new `conversation_id`. The handler saves it against your user before the answer arrives.

Add matching routes for the other calls your chat makes. Each one checks `ownsConversation` first:

| Your route | Calls |
| - | - |
| Load a conversation | [`GET /v0/chat/{conversation_id}`](https://docs.decimal.app/api-reference/chat/get-conversation) |
| Rate an answer | [`POST /v0/chat/{conversation_id}/feedback`](https://docs.decimal.app/api-reference/chat/rate-an-answer) |
| Talk to a person | [`POST /v0/chat/{conversation_id}/escalate`](https://docs.decimal.app/api-reference/escalation/escalate-to-ticketing-integration) |

### Tell the agent who's asking

The `user` object holds the customer's `name` and `email`. The agent uses the name to address them. It's saved on the conversation, so follow-ups can leave it out.

The agent treats `user` as context, not proof of identity. [Policies](https://docs.decimal.app/policies.md) that need a [signed-in visitor](https://docs.decimal.app/policies.md#signed-in-visitors) don't run through the Chat API, and customers who ask about those topics get the agent's normal answer instead.

## 3. Read the stream in the browser

`EventSource` can only send `GET` requests, so read the stream with `fetch`:

```ts theme={null}
type ChatEvent = { event: string; data: any };

async function* streamMessage(body: {
  message: string;
  conversationId?: string;
  idempotencyKey: string;
}): AsyncGenerator<ChatEvent> {
  const res = await fetch('/api/support-chat', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  if (!res.ok) {
    throw new ChatRequestError(res.status, await res.json().catch(() => null));
  }
  if (!res.headers.get('Content-Type')?.startsWith('text/event-stream')) {
    yield { event: 'message.started', data: await res.json() };
    return;
  }

  const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
  let buffer = '';
  for (;;) {
    const { value, done } = await reader.read();
    if (done) return;
    buffer += value;
    let end;
    while ((end = buffer.indexOf('\n\n')) !== -1) {
      const block = buffer.slice(0, end);
      buffer = buffer.slice(end + 2);
      let event = 'message';
      let data = '';
      for (const line of block.split('\n')) {
        if (line.startsWith('event: ')) event = line.slice(7);
        if (line.startsWith('data: ')) data += line.slice(6);
      }
      if (data) yield { event, data: JSON.parse(data) };
    }
  }
}
```

Blocks with no `data:` line are keep-alives, sent every 15 seconds, and are skipped.

A retry that reuses an [idempotency key](https://docs.decimal.app/api-reference/idempotency.md) gets the original `202` JSON body instead of a stream. The code above turns that into a `message.started` event. You then [poll for the answer](#if-you-cant-stream).

### Handle each event

| Event | What to show |
| - | - |
| `message.started` | A typing indicator. Store `conversation_id` and `message_id`. |
| `tool_call.started` | What the agent is doing, such as "Searching the docs". |
| `tool_call.completed` | Mark that step done. `refs` lists what it found. |
| `message.completed` | The answer in `message`. Clear the indicator. |
| `message.failed` | An error with a way to [retry](#8-handle-errors). |

The answer arrives whole in `message.completed`. There's no word-by-word text. Use the tool events to show progress while the customer waits.

```ts theme={null}
for await (const { event, data } of streamMessage({ message, conversationId, idempotencyKey })) {
  switch (event) {
    case 'message.started':
      conversationId = data.conversation_id;
      showTyping();
      break;
    case 'tool_call.started':
      showStep(data.id, stepLabel(data));
      break;
    case 'tool_call.completed':
      completeStep(data.id);
      break;
    case 'message.completed':
      showAnswer(data.message);
      break;
    case 'message.failed':
      showError(data.error);
      break;
  }
}
```

Tool names depend on what the agent can use. The tools it can call change with your [Policies](https://docs.decimal.app/policies.md), connected MCP servers, and custom tools. Map the names you want to label and fall back to a generic one:

```ts theme={null}
function stepLabel(call: { name: string }) {
  if (call.name === 'searchPublicKB') return 'Searching the docs';
  if (call.name.toLowerCase().includes('code')) return 'Reading the code';
  return 'Looking into it';
}
```

`input` holds the tool's arguments, such as a search query. Show them only if they'd make sense to your customer.

### If you can't stream

Leave out `stream`. Sending returns `202` with `conversation_id` and `message_id`. Poll [`GET /v0/chat/{conversation_id}`](https://docs.decimal.app/api-reference/chat/get-conversation) until `status` is `completed` or `failed`.

Every poll counts toward your [rate limits](https://docs.decimal.app/api-reference/rate-limits.md), and all your customers share your token's 120 requests a minute. Polling every 2 seconds uses 30 of those per waiting customer, so streaming scales much further. If you poll, wait at least 2 seconds between requests and honor `Retry-After` on a `429`.

## 4. Show the answer

An answer is a `ConversationMessage`:

```json theme={null}
{
  "role": "assistant",
  "message_id": "xyz789",
  "content": "Open **Settings → SSO** and choose your provider.[¹](https://docs.example.com/sso)",
  "sources": [
    { "type": "kb", "title": "Set up SSO", "url": "https://docs.example.com/sso" }
  ],
  "outcome": "answered"
}
```

* **`content`** is Markdown. Render it with a Markdown library that sanitizes HTML, because answers can quote what customers typed. Citations are already inline as superscript links, such as `[¹](https://...)`.
* **`sources`** lists each knowledge article (`kb`) or code file (`code`) the answer drew on. Show them as a list under the answer. `url` and `snippet` aren't always present.
* **`message_id`** identifies this answer. Keep it to [rate the answer](#6-let-customers-rate-answers).
* **`outcome`** says how the agent resolved the message. Use it to [offer a person](#7-hand-off-to-a-person).

## 5. Take follow-up questions

Send the next message with the same `conversation_id`. The agent keeps the earlier messages as context.

A conversation answers one message at a time. Disable your send button from `message.started` until `message.completed` or `message.failed`. A message sent while the conversation is still working gets `409` with code `conflict`.

To restore a chat after a page reload, look up the customer's saved `conversation_id` and load it with [`GET /v0/chat/{conversation_id}`](https://docs.decimal.app/api-reference/chat/get-conversation). `messages` holds the whole conversation, oldest first, in the same shape as above. If `status` is still `processing`, show the typing indicator and poll until it finishes.

## 6. Let customers rate answers

Add a helpful / not helpful control under each answer and send the rating to [`POST /v0/chat/{conversation_id}/feedback`](https://docs.decimal.app/api-reference/chat/rate-an-answer):

```bash theme={null}
curl -X POST https://api.getdecimal.ai/v0/chat/abc123/feedback \
  -H "Authorization: Bearer sk-de-..." \
  -H "Content-Type: application/json" \
  -d '{
    "message_id": "xyz789",
    "rating": "not_helpful",
    "comment": "Nothing about SAML."
  }'
```

`rating` is `helpful` or `not_helpful`. `comment` is optional, up to 2,000 characters. Leave out `message_id` to rate the latest answer. Rating the same answer again replaces the earlier rating, so customers can change their mind.

You can rate answers only once the conversation is `completed`.

## 7. Hand off to a person

Show a **Talk to a person** button on every conversation. Bring it forward when the latest answer's `outcome` says the customer needs one:

| `outcome` | Meaning | Suggested UI |
| - | - | - |
| `answered` | Answered from your sources | Keep the button in its usual place |
| `clarifying` | Asked the customer a question | Wait for their reply |
| `knowledge_gap` | Your sources don't cover it | Offer the button |
| `needs_human` | A person should handle it, such as an account change | Offer the button |
| `handoff_requested` | The customer asked for a person | Escalate, or ask them to confirm |
| `out_of_scope` | Unrelated to your product | Keep the button in its usual place |

When the customer asks for a person, call [`POST /v0/chat/{conversation_id}/escalate`](https://docs.decimal.app/api-reference/escalation/escalate-to-ticketing-integration) with your helpdesk and their name and email. Decimal opens a ticket with the transcript and a summary:

```bash theme={null}
curl -X POST https://api.getdecimal.ai/v0/chat/abc123/escalate \
  -H "Authorization: Bearer sk-de-..." \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 0b8e2f4a-..." \
  -d '{"integration": "zendesk", "email": "jane@example.com", "name": "Jane Doe"}'
```

Then tell the customer how your team will reply, such as by email. Messages sent after this aren't added to the ticket, so close the chat or point the customer to the ticket.

A conversation can be escalated once, and only when it's `completed`. A second call gets `409` with code `conflict`. See the [Escalation API](https://docs.decimal.app/api-reference/escalation/overview.md) for each helpdesk's fields.

## 8. Handle errors

Errors share [one shape](https://docs.decimal.app/api-reference/errors.md). Branch on `error.code`, and retry when `error.retryable` is `true`.

| What happened | What to do |
| - | - |
| The request timed out, or your server got no response | Retry with the same `Idempotency-Key`. Decimal won't send the message twice. |
| The stream dropped before `message.completed` | The answer is still saved. Poll `GET /v0/chat/{conversation_id}` until it finishes. |
| `message.failed`, or `status: "failed"` | Show an error with a **Try again** button that sends the message again with a new `Idempotency-Key`. |
| `409` `conflict` on send | The previous message is still running. Wait for it, then send. |
| `429` `rate_limited` | Wait `Retry-After` seconds. |

Create one `Idempotency-Key` per message the customer sends, such as with `crypto.randomUUID()`, and reuse it only to retry that same send.

## Before you launch

* The token lives only on your server, with only the scopes you need.
* Your server checks that each `conversation_id` belongs to the signed-in customer.
* Answers render as sanitized Markdown, with `sources` shown as citations.
* The send button is disabled while a message is running.
* A dropped stream recovers by polling, and `message.failed` offers a retry.
* **Talk to a person** escalates once, and the customer knows how your team will reply.
* Test a few real questions and review them under [API conversations](https://docs.decimal.app/channels/conversations.md#review-an-api-request).


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