> For the complete documentation index, see [llms.txt](https://chatbotiq.gitbook.io/chatbotiq-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://chatbotiq.gitbook.io/chatbotiq-docs/how-to-guides/use-the-chat-api.md).

# Use the Chat API

The Chat API lets you send messages to your bot and receive streaming responses programmatically. This is the same API that powers the embedded widget -- you can use it to build custom integrations, mobile apps, or backend services.

***

## Prerequisites

* Your bot must be set to **Public** privacy mode.
* You need your **bot ID** (find it in the Embed tab of the Playground).

***

## Send a message (curl)

```bash
curl -N -X POST https://app.chatbotiq.eu/v1/public/chat/stream \
  -H "Content-Type: application/json" \
  -d '{
    "bot_id": "YOUR-BOT-ID",
    "message": "How do I get started?",
    "session_id": "my-session-123"
  }'
```

The `-N` flag disables curl's output buffering so you see the streaming response in real time.

***

## Send a message (JavaScript)

```javascript
async function chat(botId, message, sessionId, conversationId) {
  const response = await fetch('https://app.chatbotiq.eu/v1/public/chat/stream', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      bot_id: botId,
      message: message,
      session_id: sessionId,
      conversation_id: conversationId
    })
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let fullResponse = '';

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

    const chunk = decoder.decode(value);
    const lines = chunk.split('\n').filter(line => line.startsWith('data: '));

    for (const line of lines) {
      const data = JSON.parse(line.slice(6));

      if (data.token) {
        fullResponse += data.token;
        process.stdout.write(data.token); // Stream to output
      }
      if (data.conversation_id) {
        console.log('\nConversation ID:', data.conversation_id);
      }
      if (data.citations) {
        console.log('\nCitations:', data.citations);
      }
    }
  }

  return fullResponse;
}
```

***

## Send a message (Python)

```python
import requests
import json

def chat(bot_id, message, session_id, conversation_id=None):
    response = requests.post(
        'https://app.chatbotiq.eu/v1/public/chat/stream',
        json={
            'bot_id': bot_id,
            'message': message,
            'session_id': session_id,
            'conversation_id': conversation_id,
        },
        stream=True
    )

    full_response = ''
    for line in response.iter_lines():
        if line and line.startswith(b'data: '):
            data = json.loads(line[6:])

            if 'token' in data:
                full_response += data['token']
                print(data['token'], end='', flush=True)
            if 'conversation_id' in data:
                print(f"\nConversation ID: {data['conversation_id']}")
            if 'citations' in data:
                print(f"\nCitations: {data['citations']}")
            if data.get('done'):
                break

    return full_response
```

***

## Continue a conversation

To send follow-up messages, include the `conversation_id` from the first response:

```bash
curl -N -X POST https://app.chatbotiq.eu/v1/public/chat/stream \
  -H "Content-Type: application/json" \
  -d '{
    "bot_id": "YOUR-BOT-ID",
    "message": "Tell me more about that",
    "session_id": "my-session-123",
    "conversation_id": "CONVERSATION-ID-FROM-FIRST-RESPONSE"
  }'
```

***

## Handle errors

| Status | Meaning                     | What to do                                     |
| ------ | --------------------------- | ---------------------------------------------- |
| 404    | Bot not found or not public | Check the bot ID and privacy mode              |
| 429    | Rate limit exceeded         | Wait and retry. Check bot rate limit settings. |
| 402    | Insufficient credits        | The workspace needs more credits.              |

***

## Related

* [Chat API Reference](/chatbotiq-docs/reference/chat-api.md) -- complete endpoint documentation
* [Bot Settings Reference](/chatbotiq-docs/reference/bot-settings.md) -- rate limits and privacy settings


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://chatbotiq.gitbook.io/chatbotiq-docs/how-to-guides/use-the-chat-api.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
