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

# Chat API

> Session-aware conversational API — the primary endpoint for product integrations.

## POST /v1/bots/:id/chat

The Chat API sends a message to a bot and receives a response. Sessions are maintained via the `X-Session-ID` header — pass the same ID across multiple calls to preserve conversation context and memory.

This is the primary endpoint for embedding Bothive agents inside your product.

## Request

```bash theme={null}
curl -X POST https://api.bothive.cloud/v1/bots/{bot_id}/chat \
  -H "Authorization: Bearer bh_sk_xxxxxxxxx" \
  -H "Content-Type: application/json" \
  -H "X-Session-ID: user_abc123" \
  -d '{
    "message": "What is my current subscription plan?",
    "context": {
      "user_name": "Jeremy",
      "company": "Acme Corp"
    }
  }'
```

### Headers

| Header          | Required    | Description                                             |
| --------------- | ----------- | ------------------------------------------------------- |
| `Authorization` |             | `Bearer bh_sk_...` — your API key                       |
| `Content-Type`  |             | `application/json`                                      |
| `X-Session-ID`  | Recommended | Stable user ID to scope memory and conversation history |
| `Accept`        | Optional    | `text/event-stream` for streaming responses             |

### Request body

| Field     | Type      | Required | Description                                                   |
| --------- | --------- | -------- | ------------------------------------------------------------- |
| `message` | `string`  |          | The user's message                                            |
| `context` | `object`  | Optional | Additional key-value context injected into the agent's prompt |
| `stream`  | `boolean` | Optional | Enable SSE streaming. Default: `false`                        |

## Response

```json theme={null}
{
  "response": "Your current plan is Pro. It renews on February 15, 2025. You have 8,432 runs remaining this month.",
  "session_id": "user_abc123",
  "run_id": "run_xyz789",
  "latency_ms": 423,
  "tokens_used": 312,
  "tools_called": ["billing.getSubscription"]
}
```

### Response fields

| Field          | Type       | Description                                       |
| -------------- | ---------- | ------------------------------------------------- |
| `response`     | `string`   | The agent's reply                                 |
| `session_id`   | `string`   | The session ID used for this run                  |
| `run_id`       | `string`   | Unique ID for this run — use to look up the trace |
| `latency_ms`   | `number`   | Total round-trip latency in milliseconds          |
| `tokens_used`  | `number`   | Total tokens consumed (prompt + completion)       |
| `tools_called` | `string[]` | List of tool capability names that were invoked   |

## Streaming (SSE)

For lower time-to-first-token and better UX, enable streaming:

```bash theme={null}
curl -X POST https://api.bothive.cloud/v1/bots/{bot_id}/chat \
  -H "Authorization: Bearer bh_sk_xxxxxxxxx" \
  -H "Content-Type: application/json" \
  -H "X-Session-ID: user_abc123" \
  -H "Accept: text/event-stream" \
  -d '{"message": "Summarize my last 5 invoices", "stream": true}'
```

Streaming response (SSE format):

```
data: {"delta": "Your last "}
data: {"delta": "5 invoices total "}
data: {"delta": "$1,247.50."}
data: {"event": "done", "run_id": "run_abc123", "latency_ms": 812}
```

## JavaScript / TypeScript example

```typescript theme={null}
// Non-streaming
const response = await fetch(
  `https://api.bothive.cloud/v1/bots/${BOT_ID}/chat`,
  {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.BOTHIVE_API_KEY}`,
      'Content-Type': 'application/json',
      'X-Session-ID': userId,
    },
    body: JSON.stringify({
      message: userMessage,
      context: { plan: user.plan, name: user.name },
    }),
  }
);

const { response: reply, run_id } = await response.json();
```

```typescript theme={null}
// Streaming with EventSource
const eventSource = new EventSource(
  `https://api.bothive.cloud/v1/bots/${BOT_ID}/chat/stream?session_id=${userId}`,
  { headers: { Authorization: `Bearer ${API_KEY}` } }
);

eventSource.onmessage = (event) => {
  const { delta, event: type, run_id } = JSON.parse(event.data);
  if (type === 'done') {
    eventSource.close();
    console.log('Run ID:', run_id);
  } else {
    appendToUI(delta);
  }
};
```

## Session management

<Info>
  Always pass a stable, unique `X-Session-ID` for each end user. This is how Bothive scopes memory and conversation history. Using the same session ID for multiple users will mix their memories.
</Info>

**Good session IDs:**

* Your database user ID: `usr_a4f9b2c1`
* A UUID you generate per user: `550e8400-e29b-41d4-a716-446655440000`

**Bad session IDs:**

* A shared constant: `"default"`
* IP address (multiple users share IPs)
* Timestamp (resets each request)

## Memory and context in chat

The Chat API automatically:

1. Loads conversation history for the given session
2. Injects persistent memory for this user
3. Merges the `context` object you pass
4. Sends everything to the model

You can override or extend what the agent knows by passing `context`:

```json theme={null}
{
  "message": "Do I qualify for a refund?",
  "context": {
    "user_plan": "pro",
    "last_payment": "2025-01-15",
    "support_tier": "priority"
  }
}
```

## Error handling

```typescript theme={null}
try {
  const res = await fetch('...', { ... });
  if (!res.ok) {
    const { error } = await res.json();
    if (error.code === 'rate_limit_exceeded') {
      // Wait and retry after error.retry_after seconds
      await sleep(error.retry_after * 1000);
    }
    throw new Error(error.message);
  }
  const data = await res.json();
} catch (err) {
  console.error('Bothive API error:', err);
}
```

## Next reads

<CardGroup cols={3}>
  <Card title="Execute API" icon="play" href="./execute" className="glass-effect" />

  <Card title="Deploy API" icon="rocket" href="./deploy" className="glass-effect" />

  <Card title="API Overview" icon="server" href="./overview" className="glass-effect" />
</CardGroup>
