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

# Onsite Chat Quickstart

> Add the Response chat widget to your site — embed it, point it at your backend, and go live.

# Onsite Chat Quickstart

The Response Chat Widget is a production-ready, AI-powered chat widget you drop into any web
application. This page gets it on your site and talking to a backend.

## 1. Embed the widget

The widget ships as a UMD bundle. Include React, the stylesheet, and the bundle, then mount it
into any container:

```html theme={null}
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<link rel="stylesheet" href="https://stateset.chat/vX.Y.Z/chat-widget.css" />
<script src="https://stateset.chat/vX.Y.Z/chat-widget.bundle.js"></script>

<div id="chat"></div>

<script>
  const api = window.ChatWidget.mount({
    container: document.getElementById('chat'),
    props: {
      companyName: 'Acme Inc.',
      agentName: 'AI Assistant',
      messageEndpoint: '/api/chat',
      threadCreateEndpoint: '/api/threads',
      provider: 'openai',
      enableStreaming: true,
      enableToolVisualization: true,
      enableSourceCitations: true,
      enableRichMessages: true,
    },
  });
</script>
```

<Warning>
  Pin a version in the CDN URL — replace `vX.Y.Z` with a real release. Pointing at a floating
  "latest" means a widget upgrade ships to your production site without you deploying anything.
</Warning>

`mount()` returns a control surface:

```js theme={null}
api.open();
api.close();
api.toggle();
```

`provider` accepts `openai`, `anthropic`, or `gemini`.

## 2. Wire up your backend

With `messageEndpoint` set, the widget POSTs JSON in this shape:

```json theme={null}
{
  "subject": "Optional conversation subject",
  "message": "Customer message text",
  "attachments": [{ "name": "screenshot.png", "type": "image/png", "size": 12345 }],
  "meta": { "department": "Support", "customFields": {} },
  "sessionId": "optional-session",
  "source": "response-chat-widget",
  "channel": "web",
  "threadId": "abc123",
  "provider": "openai"
}
```

Your endpoint should return an object the widget can render. If your API has a different shape,
you don't need to change it — override both directions:

| Hook                                            | Purpose                                                                       |
| ----------------------------------------------- | ----------------------------------------------------------------------------- |
| `buildMessagePayload(payload, outgoingMessage)` | Reshape the outgoing request                                                  |
| `parseResponse(response)`                       | Map your response to `{ text, suggestions, threadId?, toolCalls?, sources? }` |

### Threads

Provide `threadEndpoint` and `threadId` to load history. The widget issues
`GET {endpoint}?threadId={id}` with optional bearer auth.

Full CRUD is available via `threadCreateEndpoint`, `threadUpdateEndpoint`, and
`threadDeleteEndpoint`, with `buildThreadRequest`, `buildThreadUrl`, `buildThreadUpdateUrl`, and
`buildThreadDeleteUrl` for custom URL shapes.

## 3. Run it locally first

```bash theme={null}
npm install
cp env.example .env       # set OPENAI_API_KEY / ANTHROPIC_API_KEY / GEMINI_API_KEY

npm run dev               # mock backend + demo widget → http://localhost:3000
npm run dev:ai            # talk to real models (needs an API key)
```

Node.js **20.17.0+** is required and enforced in CI.

| Command            | Purpose                                            |
| ------------------ | -------------------------------------------------- |
| `npm run dev`      | Mock server with streaming and ChatKit simulations |
| `npm run dev:ai`   | AI-powered server (OpenAI/Anthropic/Gemini)        |
| `npm run build`    | Produces `public/chat-widget.bundle.js` and CSS    |
| `npm test`         | Jest suite (jsdom + Testing Library)               |
| `npm run validate` | Format check → lint → test, as CI runs it          |

<Tip>
  Start against the mock server. It exercises streaming, tool visualization, and citations without
  spending API credits or needing a working backend.
</Tip>

## 4. Show commerce records

The widget header carries tabs for **Chat**, **Orders**, **Products**, **Subscriptions**,
**Returns**, and **Exchanges**, driven by the `records` prop:

```js theme={null}
window.ChatWidget.mount({
  container: document.getElementById('chat'),
  props: {
    records: {
      products: [{
        id: 'SKU-44819',
        name: 'Luna Smart Bottle',
        status: 'In Stock',
        price: '$89.00',
        stock: 182,
        rating: 4.8,
        badges: ['Top seller'],
      }],
      orders: [{
        id: 'ORD-9001',
        status: 'Processing',
        amount: '$199.00',
        customer: 'Jordan Lee',
        summary: 'Home gym starter kit',
        metrics: [{ label: 'Items', value: '4' }],
        nextAction: 'Confirm inventory with warehouse',
      }],
      returns: [], subscriptions: [], exchanges: [],
    },
  },
});
```

Each category renders status badges, metrics, and summary cards automatically. Orders, returns,
exchanges, and subscriptions have a **List** mode; products support **List** and **Carousel**.

<Note>
  Omit `records` entirely and sample data is shown, so the UI never looks empty in a demo. Make
  sure you pass real data before going to production — otherwise customers see the samples.
</Note>

## Feature flags

| Prop                      | Effect                                            |
| ------------------------- | ------------------------------------------------- |
| `enableStreaming`         | Token-by-token streaming responses                |
| `enableToolVisualization` | Shows tool calls as the agent makes them          |
| `enableSourceCitations`   | Renders source citations under answers            |
| `enableRichMessages`      | Markdown, syntax highlighting, forms, and actions |

Other capabilities: reactions, transcript export, programmable actions, responsive fullscreen
with iPhone safe-area handling, and built-in locale packs with translation overrides and
automatic RTL layout.

## Next steps

<CardGroup cols={2}>
  <Card title="Widget reference" icon="sliders" href="/stateset-response/response-chat-widget">
    Configuration, revenue capture v2, and deployment.
  </Card>

  <Card title="Response Public API" icon="code" href="/stateset-response/response-public-api">
    Build the agent behind the chat.
  </Card>
</CardGroup>
