# Chat with Chatbot

Send a question to a chatbot and receive a response. By default, the endpoint returns JSON. If you set `stream: true`, it returns a server-sent event (SSE) stream that can be consumed from a server with `fetch()`. This endpoint also returns a `chatlogId` for maintaining conversation context and a list of sources used for the answer (max 5), ordered by relevance.

## Endpoint

```
POST https://app.wonderchat.io/api/v1/chat
```

## Request Parameters

| Parameter    | Type    | Required | Description                                                               |
| ------------ | ------- | -------- | ------------------------------------------------------------------------- |
| `chatbotId`  | string  | ✅ Yes    | The ID of the chatbot you want to chat with                               |
| `question`   | string  | ✅ Yes    | The question you wish to ask your chatbot                                 |
| `chatlogId`  | string  | ❌ No     | The ID of your current chat session for conversation continuity           |
| `context`    | string  | ❌ No     | Additional custom context about the chat session (e.g., user information) |
| `contextUrl` | string  | ❌ No     | URL of the page the user is on to provide additional context              |
| `stream`     | boolean | ❌ No     | Set to `true` to receive the answer as an SSE stream instead of JSON      |

## Example Request (JSON Response)

```bash
curl --location --request POST 'https://app.wonderchat.io/api/v1/chat' \
--header 'Content-Type: application/json' \
--data-raw '{
  "chatbotId": "YOUR_CHATBOT_ID",
  "question": "Hello there!",
  "chatlogId": "YOUR_CHATLOG_ID",
  "context": "You are speaking with John, a 28 year old salesperson from Canada. English is not his native language, so please refrain from using complicated words.",
  "contextUrl": "https://yourwebsite.com/john-info",
  "stream": false
}'
```

## JSON Response Format

```json
{
  "id": "cm1234567890",
  "response": "Hello there, how may I help you?",
  "chatlogId": "cli7n0vvs000008l43ez2bxa0",
  "sources": [
    {
      "url": "https://www.yourwebsite.com/source1",
      "title": "About Us"
    }
  ]
}
```

## Response Fields

| Field             | Type   | Description                                           |
| ----------------- | ------ | ----------------------------------------------------- |
| `id`              | string | Unique identifier for this message                    |
| `response`        | string | The chatbot's response to your question               |
| `chatlogId`       | string | Unique identifier for this chat session               |
| `sources`         | array  | List of sources used to generate the response (max 5) |
| `sources[].url`   | string | URL of the source document                            |
| `sources[].title` | string | Title of the source document                          |

## Streaming

When `stream` is set to `true`, the response content type is `text/event-stream`.

### Streaming Request

```bash
curl --no-buffer --location --request POST 'https://app.wonderchat.io/api/v1/chat' \
--header 'Content-Type: application/json' \
--header 'Accept: text/event-stream' \
--data-raw '{
  "chatbotId": "YOUR_CHATBOT_ID",
  "question": "Hello there!",
  "chatlogId": "YOUR_CHATLOG_ID",
  "stream": true
}'
```

### Streaming Event Types

| Event      | Data Shape                                                               | Description                       |
| ---------- | ------------------------------------------------------------------------ | --------------------------------- |
| `metadata` | `{"chatlogId": "..."}`                                                   | Initial metadata with chatlog ID  |
| `chunk`    | `{"delta": "partial response text"}`                                     | Partial response text             |
| `done`     | `{"id": "...", "response": "...", "chatlogId": "...", "sources": [...]}` | Final payload with full response  |
| `error`    | `{"error": "message"}`                                                   | Error message if something failed |

### Example Stream

```
event: metadata
data: {"chatlogId":"cli7n0vvs000008l43ez2bxa0"}

event: chunk
data: {"delta":"Hello"}

event: chunk
data: {"delta":" there, how may I help you?"}

event: done
data: {"id":"cm1234567890","response":"Hello there, how may I help you?","chatlogId":"cli7n0vvs000008l43ez2bxa0","sources":[{"url":"https://www.yourwebsite.com/source1","title":"About Us"}]}
```

### Server Consumption Example (Node.js)

Use `fetch()` and read the response body as a stream. `EventSource` is not suitable here because this endpoint uses `POST`.

```js
const response = await fetch("https://app.wonderchat.io/api/v1/chat", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Accept: "text/event-stream",
  },
  body: JSON.stringify({
    chatbotId: "YOUR_CHATBOT_ID",
    question: "Hello there!",
    chatlogId: "YOUR_CHATLOG_ID",
    stream: true,
  }),
});

const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  buffer += decoder.decode(value, { stream: true });
  const frames = buffer.split("\n\n");
  buffer = frames.pop() ?? "";

  for (const frame of frames) {
    const lines = frame.split("\n");
    const event = lines.find((line) => line.startsWith("event:"))?.slice(6).trim();
    const data = lines.find((line) => line.startsWith("data:"))?.slice(5).trim();

    if (!event || !data) continue;

    const payload = JSON.parse(data);

    if (event === "chunk") {
      process.stdout.write(payload.delta);
    }

    if (event === "done") {
      console.log("\n\nFinal payload:", payload);
    }

    if (event === "error") {
      throw new Error(payload.error);
    }
  }
}
```

## Use Cases

* **Customer Support**: Integrate chatbot responses into your support system
* **Website Chat**: Power your website's chat widget
* **Mobile Apps**: Add conversational AI to your mobile applications
* **Workflow Automation**: Chain chatbot responses with other automated processes
* **Real-time Streaming**: Display responses progressively for better UX


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.wonderchat.io/api-reference/chat.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
